在我的程序中,我在有限的 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