如何在c中使用system()命令执行进程的pid

新手上路,请多包涵

当我们使用 system() 命令时,程序等待它完成,但我正在执行一个 process 使用 system() 并使用负载平衡服务器,因为哪个程序进入下一行就在执行系统命令之后。请注意, process 可能不完整。

 system("./my_script");

// after this I want to see whether it is complete or not using its pid.
// But how do i Know PID?
IsScriptExecutionComplete();

原文由 EmptyData 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 888
2 个回答

简单的答案:你不能。

system() 的目的是在命令执行时进行阻塞。

但你可以像这样“作弊”:

 pid_t system2(const char * command, int * infp, int * outfp)
{
    int p_stdin[2];
    int p_stdout[2];
    pid_t pid;

    if (pipe(p_stdin) == -1)
        return -1;

    if (pipe(p_stdout) == -1) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        return -1;
    }

    pid = fork();

    if (pid < 0) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        close(p_stdout[0]);
        close(p_stdout[1]);
        return pid;
    } else if (pid == 0) {
        close(p_stdin[1]);
        dup2(p_stdin[0], 0);
        close(p_stdout[0]);
        dup2(p_stdout[1], 1);
        dup2(::open("/dev/null", O_RDONLY), 2);
        /// Close all other descriptors for the safety sake.
        for (int i = 3; i < 4096; ++i)
            ::close(i);

        setsid();
        execl("/bin/sh", "sh", "-c", command, NULL);
        _exit(1);
    }

    close(p_stdin[0]);
    close(p_stdout[1]);

    if (infp == NULL) {
        close(p_stdin[1]);
    } else {
        *infp = p_stdin[1];
    }

    if (outfp == NULL) {
        close(p_stdout[0]);
    } else {
        *outfp = p_stdout[0];
    }

    return pid;
}

在这里,您不仅可以拥有进程的 PID ,还可以拥有 STDINSTDOUT 。玩得开心!

原文由 GreenScape 发布,翻译遵循 CC BY-SA 3.0 许可协议

我自己不是这方面的专家,但是如果您查看 system 的手册页

system() 通过调用 /bin/sh -c 命令执行 command 中指定的命令,并在命令完成后返回

您可以在您正在执行的命令/脚本中进入后台(并立即返回),但我认为系统中没有针对这种情况的具体规定。

我能想到的想法是:

  1. 您的命令可能会通过返回码返回 pid。
  2. 您的代码可能希望在活动进程中查找命令的名称(例如,类 unix 环境中的 /proc API)。
  3. 您可能想使用 fork / exec 自己(而不是通过 SHELL)启动命令

原文由 jsantander 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题