【问题标题】:When to use waitpid() to find status of background process何时使用 waitpid() 查找后台进程的状态
【发布时间】:2016-01-19 20:58:36
【问题描述】:

我正在尝试编写基本的 shell 程序来管理后台进程的作业控制。我了解将进程发送到您调用fork() 的后台,但不要在父进程中等待。但是,我也知道您需要使用 WNOHANG 选项调用 waitpid() 以获取已完成执行的进程的状态。我的问题是何时以及如何在我的代码中调用 waitpid() 以了解孩子何时完成。到目前为止,我只是在后台执行一个进程:

for (;;) {
    char buff[PATH_MAX + 1];                    
    char *cwd = getcwd(buff, PATH_MAX + 1);
    printf("%s/", cwd); 
    char *cmd = readline("shell>");  //This code just sets up a cmd prompt 
    if (strcmp(tokList[0], bgCmd) == 0) {
        //If the user inputs 'bg' then run the command in the background parent
        pid_t child_pid = fork();
        if (child_pid == 0) {
            execvp(bgTokList[0], bgTokList);  // This array contains just the arguments to be executed
            perror("execvp");
            return -1;
        } else {
            //parent
        }
    }
}

【问题讨论】:

    标签: c fork jobs waitpid


    【解决方案1】:

    当子进程完成时,父进程将收到信号SIGCHLD。然后,您的信号处理程序可以获取状态。

    Using an existing example,您可以根据自己的需要进行修改。

    【讨论】:

      猜你喜欢
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多