简体   繁体   English

如何让父进程等待所有子进程完成?

[英]How to make parent wait for all child processes to finish?

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 waits for a child process to terminate, and returns that child process's pid . wait等待一个子进程终止,并返回子进程的pid On error (eg when there are no child processes), -1 is returned. 出错时(例如,当没有子进程时),返回-1 So, basically, the code keeps waiting for child processes to finish, until the wait ing errors out, and then you know they are all finished. 所以,基本上,代码一直等待子进程完成,直到wait出错,然后你知道它们都已完成。

POSIX defines a function: wait(NULL); . POSIX定义了一个函数: wait(NULL); It's the shorthand for waitpid(-1, NULL, 0); 它是waitpid(-1, NULL, 0);的简写waitpid(-1, NULL, 0); , which will suspends the execution of the calling process until any one child process exits. ,它将暂停执行调用进程,直到任何一个子进程退出。 Here, 1st argument of waitpid indicates wait for any child process to end. 这里, waitpid第一个参数表示等待任何子进程结束。

In your case, have the parent call it from within your else branch. 在您的情况下,让父母从您的else分支中调用它。

Use waitpid() like this: 像这样使用waitpid():

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

Just use:只需使用:

while(wait(NULL) > 0);

This ensures that you wait for ALL the child processes and only when all have returned, you move to the next instruction.这确保您等待所有子进程,并且只有当所有子进程都返回时,您才移动到下一条指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM