Fork() 与多个 children 并等待所有这些完成

Fork() with multiple children and with waiting for all of them to finish

我想在 C 中创建一个程序,我在其中使用 fork() 创建多个 children,然后等待它们全部完成并执行 parent 代码(仅一次)。 我尝试使用 for 循环和两个分叉,但我遇到了一个问题:要么 parent 代码最后不是 运行,要么 children 不是 运行 并行。

//Number of processes I want to create
int processes = 6;

pid_t *main_fork = fork();

    if(main_fork ==0){

      for(int i=0;i<processes;i++){
        pid_t *child_fork = fork();

        if(child_fork ==0){

           // child code
           exit(0);
        }
       else if(child_fork >0){
        //And here is the problem, with the wait: children don't 
        //run parallel and if I delete it, the main parent code doesn't run 
         wait(NULL);
       }else{
        // Child fork failed
         printf("fork() failed!\n");
         return 1;
       }
      }
    }else if(main_fork >0){

      wait(NULL);
      //Main parent code - here I want to do something only once after all 
      //children are done

    }else{
      // Main fork failed
      printf("fork() failed!\n");
      return 1;
    }

如果有人可以修复我的代码,或者写出更好的解决方案来解决这个问题,我将不胜感激!

如果你想让所有的children并行到运行,你必须等待所有的children已经启动。否则你开始一个 child,等待它完成,开始一个新的,等待那个完成,开始第三个,等待第三个完成,等等......

所以你通常想要做的是开始所有的 children 并将所有的 pid_t 放在一个数组中,当你完成后你可以调用 wait() for每个 pid_t

这是适合您的情况的简单且足够好的解决方案。

这是一个可以解决您的问题的示例代码:

pid_t children[processes];

for(int i=0; i<processes; i++)
  {
    pid_t child = fork();

    if(child == 0)
      {
        // child code
         ....
        // We call _exit() rather than exit() since we don't want to clean up
        // data structures inherited from parent
        _exit(0);
      }
    else if (child == -1)
      {
         // Child fork failed
         fprintf(stderr, "myprog: fork failed, %s", strerror(errno));

         // Do real cleanup on failure is to complicated for this example, so we
         // just exit           
         exit(EXIT_FAILURE);
      }
    children[i] = child;
  }
// Do something if you want to do something before you expect the children to exit
.... 

for(int i=0; i<processes; i++)
  {
    pid_t child = children[i];

    int status;
    waitpid(child, &status, );

    // Do something with status
 }

当然,这不是一个适合任何情况的完整示例。有时你必须告诉 children 他们什么时候应该退出。其他时候children不是一下子started/stopped,还得玩异步事件等等...