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

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

问题描述

在我的计划,我分叉(平行)子进程在有限while循环和他们每个人做的exec。我想父进程恢复执行(这个while循环后点),所有的孩子都结束之后。我应该怎么办呢?

我尝试了好几种方法。在一种方法中,我做了父母暂停while循环之后并派从只有当waitpid函数返回错误ECHILD(无子剩余)SIGCHLD处理程序,但我面对这种方法的问题的一些条件,甚至之前父已完成分叉的所有进程,retStat变-1

 无效sigchld_handler(INT预兆报){
        将为pid_t PID;
        而((PID = waitpid函数(-1,NULL,WNOHANG))大于0);
        如果(错误== ECHILD){
        retStat = -1;
        }
    }    ** //父进程code **
    retStat = 1;
    而(一些条件){
       做叉(和exec);
    }    而(retStat大于0)
        暂停();
//这是地步,我想执行只恢复时,所有的孩子都完成


解决方案

而不是调用 waitpid函数中的信号处理程序,为什么不创建一个循环,你已付出终究流程如下:

 而(PID = waitpid函数(-1,NULL,0)){
   如果(错误== ECHILD){
      打破;
   }
}

该计划应在循环,直到有没有更多的孩子挂起。然后,它会掉下来,程序将继续进行。作为一个额外的奖金,循环阻塞 waitpid函数而孩子们正在运行,所以你不要在你等候需要一个繁忙的循环。

您也可以使用等待(NULL)这应该是等同于 waitpid函数(-1,NULL,0)。如果没有什么别的需要在SIGCHLD做的,你可以将其设置为SIG_IGN。

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

解决方案

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;
   }
}

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 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天全站免登陆