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

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

问题描述

我希望有人可以阐明如何让父级等待 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.因此,基本上,代码会一直等待子进程完成,直到wait ing错误出来,然后您就知道它们都已完成.

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