对于 waitpid,我如何知道 child 是否完成了它的进程?

For waitpid, how do I know if the child finishes its process?

首先,我 fork 一个 child 来做一些事情, 我使用 waitpid(-1, &child_status, WNOHANG);在 parent 让 parent 继续而不是等待 child 完成。

我怎么知道 child 何时完成了它的进程?

您可以为 SIGCHLD 设置一个信号处理程序,它会在 child 进程退出时自动发送。

然后信号处理器可以设置一个全局标志,该标志可以在程序的其他部分定期检查。如果设置了标志,调用 waitwaitpid 以获取 child 的退出状态。

int child_exit_flag = 0;

void child_exit(int sig)
{
    child_exit_flag = 1;
}

...

signal(SIGCHLD, child_exit);

...

if (child_exit_flag) {
    pid_t pid;
    int status;

    child_exit_flag = 0;
    pid = wait(&status);
    printf("child pid %d exited with status %d\n", pid, status);
}