何时使用waitpid()查找后台进程的状态

时间:2016-01-19 20:58:37

标签: c fork jobs waitpid

我正在尝试编写基本的shell程序,它将使用后台进程管理作业控制。我理解将进程发送到您调用fork()的后台,但不要在父进程中等待它。但是,我也知道您需要使用waitpid()选项调用WNOHANG以获取已完成执行的进程的状态。我的问题是何时以及如何在我的代码中调用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
        }
    }
}

1 个答案:

答案 0 :(得分:2)

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

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