c - 如何在父级继续之前等待所有子级终止?

标签 c fork multiprocessing wait

我正在做一些并行编程(多处理),我需要父级:

  1. fork 几个子项

  2. 创建所有子项后,只需等待所有子项终止

  3. 终止所有子级后,再做一些其他工作。

这是我尝试过的:

 int main(int argc, char **argv[])
{

  int j, i;
  pid_t children[3];
  int pid;

  // Fork the processes
  for(j = 0; j < 3; j++){
    if((children[j] = fork()) == 0){
      // Child process
      for(i = 0; i < 2; i++){
        printf("child %d printing: %d\n", j, i);
      }
    }else {
        // In parent now
        while (pid = waitpid(-1, NULL, 0)) {
            if (errno == ECHILD) {
                break;
            }
        }
        
        printf("all children terminated. in parent now\n");
    }
  }

  return 0;
}

没有给出正确的输出。 “所有 child 都终止了。现在在 parent 中”甚至在所有 child 都死之前就被打印了好几次。另外,对于每个进程,我应该只看到 2 个输出,但我看到了更多。

最佳答案

这就是您想要实现的目标吗?我刚刚为每个子项设置了一个简单的计数,并带有延迟以增加并行化可见性。

#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char **argv[])
{
  int i, j, k;
  int pid;

  // Fork the processes
  for(j = 0; j < 3; j++)
  {
    if (fork() == 0)
    {
        printf("starting child %d\n", j);
        // Child process - do your child stuff
        for (i = 0; i < 5; ++i)
        {
          for (k = 0; k < 10000000; ++k);
          printf("child %d printing: %d\n", j, i);
        }
         printf("child %d ending\n", j);
        // then just quit
        exit(0);
    }
  }

  j = 1;
  while (wait(NULL) > 0)
  {
    printf("%d child completed\n", j++);
  }

  // In parent now
  printf("all children terminated. in parent now\n");

  return 0;
}

我得到的输出是

starting child 0
starting child 1
child 0 printing: 0
starting child 2
child 1 printing: 0
child 0 printing: 1
child 2 printing: 0
child 1 printing: 1
child 0 printing: 2
child 0 printing: 3
child 2 printing: 1
child 1 printing: 2
child 1 printing: 3
child 0 printing: 4
child 0 ending
child 2 printing: 2
1 child completed
child 1 printing: 4
child 1 ending
2 child completed
child 2 printing: 3
child 2 printing: 4
child 2 ending
3 child completed
all children terminated. in parent now

关于c - 如何在父级继续之前等待所有子级终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465284/

相关文章:

python - 安全退出多进程 python 应用程序

python多处理从多处理队列访问数据不读取所有数据

c - 在 Code::Blocks 中使用非标准函数

c - 嵌套线程创建期间的数据竞争

c - 在 C 上使用 fork 进程失败 while 循环

c++ - setitimer 信号似乎只在 fork 之后才有效

使用 fork() 创建具有指定数量子进程的多进程

c - TCP C 程序自动重新连接到客户端

使用共享内存时子进程挂起?

python - 我如何在 python 多处理池 apply_async 中使用关键字参数