在父进程恢复执行之前等待所有子进程 UNIX
在我的程序中,我在有限的 while 循环中分叉(并行)子进程,并对每个子进程执行 exec 。我希望父进程仅在所有子进程终止后才恢复执行( while 循环之后的点)。我该怎么做呢?
我尝试了几种方法。在一种方法中,我让父进程在 while 循环后暂停,并仅当 waitpid 返回错误 ECHILD(没有剩余子进程)时从 SIGCHLD 处理程序发送一些条件,但我在这种方法中面临的问题甚至在父进程完成分叉所有进程之前, retStat 变为-1
void sigchld_handler(int signo) {
pid_t pid;
while((pid= waitpid(-1,NULL,WNOHANG)) > 0);
if(errno == ECHILD) {
retStat = -1;
}
}
**//parent process code**
retStat = 1;
while(some condition) {
do fork(and exec);
}
while(retStat > 0)
pause();
//This is the point where I want execution to resumed only when all children have finished
In my program I am forking (in parallel) child processes in a finite while loop and doing exec on each of them. I want the parent process to resume execution (the point after this while loop ) only after all children have terminated. How should I do that?
i have tried several approaches. In one approach, I made parent pause after while loop and sent some condition from SIGCHLD handler only when waitpid returned error ECHILD(no child remaining) but the problem I am facing in this approach is even before parent has finished forking all processes, retStat becomes -1
void sigchld_handler(int signo) {
pid_t pid;
while((pid= waitpid(-1,NULL,WNOHANG)) > 0);
if(errno == ECHILD) {
retStat = -1;
}
}
**//parent process code**
retStat = 1;
while(some condition) {
do fork(and exec);
}
while(retStat > 0)
pause();
//This is the point where I want execution to resumed only when all children have finished
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与其在信号处理程序中调用
waitpid
,为什么不在分叉所有进程后创建一个循环,如下所示:程序应该挂在循环中,直到不再有子进程。然后它就会掉下来,程序将继续进行。作为额外的好处,当子进程运行时,循环将在
waitpid
上阻塞,因此您在等待时不需要繁忙的循环。您还可以使用
wait(NULL)
,它应该相当于waitpid(-1, NULL, 0)
。如果您不需要在SIGCHLD中执行其他操作,则可以将其设置为SIG_DFL。Instead of calling
waitpid
in the signal handler, why not create a loop after you have forked all the processes as follows:The program should hang in the loop until there are no more children. Then it will fall out and the program will continue. As an additional bonus, the loop will block on
waitpid
while children are running, so you don't need a busy loop while you wait.You could also use
wait(NULL)
which should be equivalent towaitpid(-1, NULL, 0)
. If there's nothing else you need to do in SIGCHLD, you can set it to SIG_DFL.我认为你应该使用
waitpid()
调用。它允许您等待“任何子进程”,因此如果您执行适当的次数,您应该是黄金。如果失败(不确定保证),您可以在循环中使用暴力方法,在每个进程上使用
NOHANG
选项执行waitpid()
你的孩子的PID,然后延迟一段时间再做一次。I think you should use the
waitpid()
call. It allows you to wait for "any child process", so if you do that the proper number of times, you should be golden.If that fails (not sure about the guarantees), you could do the brute-force approach sitting in a loop, doing a
waitpid()
with theNOHANG
option on each of your child PIDs, and then delaying for a while before doing it again.