gpt4 book ai didi

c++ - 如何确保 `waitpid(-1, &stat, WNOHANG)` 收集所有子进程

转载 作者:太空狗 更新时间:2023-10-29 20:29:01 26 4
gpt4 key购买 nike

摘自Unix Network Programming Vol1 Third Edition Section 5.10 wait and waitpid functions

#include    "unp.h"    
void
sig_chld(int signo)
{
pid_t pid;
int stat;
while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) {
printf("child %d terminated\n", pid);
}
return;
}

...
// in server code
Signal(SIGCHLD, sig_chld); // used to prevent any zombies from being left around
...

..
// in client code
The client establishes five connection with the server and then immediately exit
...

引用 waitpid :

Return Value

waitpid(): on success, returns the process ID of the child whose state has changed; if WNOHANG was specified and one or more child(ren) specified by pid exist, but have not yet changed state, then 0 is returned. On error, -1 is returned.

根据上述文档,如果此时没有子进程终止,waitpid 将返回 0。如果我理解正确的话,这将导致 sig_chld 函数从 while 语句中中断。

问题> 那么我们如何保证这个信号处理程序能够确保收集到所有终止的子进程?

最佳答案

while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) {
printf("child %d terminated\n", pid);

如果你没有 child 要处理,你就不会在信号处理程序中。循环是因为当您在处理程序本身中时,第二个或第三个 child 可能已经更改或终止发送不会排队的 SIGCHLD。因此,循环实际上可以防止您错过那些可能死去的 child 。当此时没有更多的 child 要收割时,它将返回 0 或错误输出 -1 (ECHILD)。

关于c++ - 如何确保 `waitpid(-1, &stat, WNOHANG)` 收集所有子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11322488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com