如何在父母继续前等待所有孩子终止?

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

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; } 

没有给出正确的输出。 “即使在所有的孩子都死了之前,所有的孩子都在父母身边被终止了”。 此外,对于每个进程,我应该只看到2个输出,但我看到更多。 任何帮助都会被贬低。

这更像是你想要达到的目标吗? 我只是为每个孩子设置一个简单的计数,延迟以增加并行化可见性。

 #include  #include  #include  #include  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 

每个孩子都在执行循环和分叉。 打印输出后需要打破j循环。 由于这些孙子女不是原始父母的孩子,并且第一代孩子从不等待他们,所以输出的顺序是未指定的。 此外,您需要将waitpid从j循环中取出,并且在所有子节点分叉之前不执行它。