如何让父进程等待所有子进程完成? [英] How to make parent wait for all child processes to finish?

查看:31
本文介绍了如何让父进程等待所有子进程完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以阐明如何让父进程等待 ALL 子进程完成,然后再继续分叉.我有要运行的清理代码,但子进程需要在这发生之前返回.

I'm hoping someone could shed some light on how to make the parent wait for ALL child processes to finish before continuing after the fork. I have cleanup code which I want to run but the child processes need to have returned before this can happen.

for (int id=0; id<n; id++) {
  if (fork()==0) {
    // Child
    exit(0);      
  } else {
    // Parent
    ...
  }
  ...
}

推荐答案

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait 等待a 子进程终止,并返回该子进程的 pid.出错时(例如,当没有子进程时),返回 -1.所以,基本上,代码一直在等待子进程完成,直到 waiting 错误出现,然后你就知道它们都完成了.

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

这篇关于如何让父进程等待所有子进程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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