要找出哪些子进程已waitpid
在您的 SIGCHLD 处理程序中终止使用:
/* SIGCHLD handler. */
static void sigchld_hdl (int sig)
{
pid_t child_pid;
/* Wait for all dead processes.
* We use a non-blocking call to be sure this signal handler will not
* block if a child was cleaned up in another part of the program. */
while ((child_pid = waitpid(-1, NULL, WNOHANG)) > 0) {
// child_pid contains the terminated child process' pid
}
}
有关更多详细信息和此代码段所基于的sscce ,请查看示例的源代码。
编辑:
所以问题是如何不仅等待孩子,而且等待所有后代。
在伪代码中:
int alive_descendants = 0;
sigchld_handler() {
decrement alive_descendants for each zombie;
}
int main() {
setup-sigchld-handler;
int fd[2];
if (pipe(fd)) { error }
to create a child:
write a single byte to fd[1]
fork off the child
in the child process:
close(fd[0]);
to create child:
write a single byte to fd[1]
fork off the child
...
in the root process:
close(fd[1]);
for each byte read from fd[0], increment alive_descendants
if alive_descendants == 0 and fd[0] is empty:
ascertain that all descendants have terminated
close(fd[0]);
}