在父进程恢复执行之前等待所有子进程 UNIX [英] Waiting for all child processes before parent resumes execution UNIX

查看:32
本文介绍了在父进程恢复执行之前等待所有子进程 UNIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我在有限的 while 循环中分叉(并行)子进程并对每个子进程执行 exec.我希望父进程仅在所有子进程终止后才能恢复执行(此 while 循环之后的点).我该怎么做?

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?

我尝试了几种方法.在一种方法中,我让父级在 while 循环后暂停,并且仅当 waitpid 返回错误 ECHILD(没有子级剩余)时才从 SIGCHLD 处理程序发送一些条件,但我在这种方法中面临的问题甚至在父级完成分叉所有进程之前,retStat 就变成了-1

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

推荐答案

与其在信号处理程序中调用waitpid,不如在fork完所有进程后创建一个循环,如下所示:

Instead of calling waitpid in the signal handler, why not create a loop after you have forked all the processes as follows:

while (pid = waitpid(-1, NULL, 0)) {
   if (errno == ECHILD) {
      break;
   }
}

程序应该挂在循环中,直到没有更多的孩子.然后它会掉下来,程序将继续.作为额外的奖励,循环将在子进程运行时阻塞 waitpid,因此您在等待时不需要繁忙的循环.

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.

你也可以使用 wait(NULL),它应该等价于 waitpid(-1, NULL, 0).如果在 SIGCHLD 中没有其他需要执行的操作,则可以将其设置为 SIG_IGN.

You could also use wait(NULL) which should be equivalent to waitpid(-1, NULL, 0). If there's nothing else you need to do in SIGCHLD, you can set it to SIG_IGN.

这篇关于在父进程恢复执行之前等待所有子进程 UNIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆