在 linux 上,如何等待多个 child 进程?

On linux, how to wait for multiple child processes?

*nix wait() 和 wait_pid() 在演示程序中工作,其中

(1) a father forks a child, wait for the child to exit

(2) and the wait function returns.

强调的是,如果爸爸不等待并保持运行,children就会退出并成为“僵尸”。

但现实世界中的 *nix 编程就像

(1) I am writing a server program,

(2) the main process works to fork some child workers,

(3) and these child workers do some job and then exit.

那么问题来了,父进程如何fork等待多个children?有没有方便的方法来做到这一点,或者设计应该有所不同?

谢谢。

三种可能:

1) 使用 waitpid 定期检查 dead children。即不时做:

    while (waitpid(-1, NULL, WNOHANG) > 0)
        continue;

2) 在信号处理程序中清理

/* SIGCHLD handler to reap dead child processes */
static void grimReaper(int sig)
{
    int savedErrno = errno;
    while (waitpid(-1, NULL, WNOHANG) > 0)
        continue;
    errno = savedErrno;
}   
int main(void) {
    ...
    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sigemptyset(&sa.sa_mask);
    sa.sa_handler = grimReaper;
    if (sigaction(SIGCHLD, &sa, NULL) == -1)
        ...
}       

3) 通过忽略 parent:

中的 SIGCHLD 来分离 children
signal(SIGCHLD, SIG_IGN);