2012-11-20 52 views
2

我在做一些並行編程(多),我需要的家長:如何等待所有孩子在父母離開之前終止?

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個輸出,但我看到更多。任何幫助都會被處理。

回答

1

這是你想要實現的更多嗎?我爲每個孩子設置了一個簡單的計數,以延長並行化可視性。

#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 

1

每個孩子正在執行循環和分叉。打印輸出後,您需要跳出j循環。由於這些孫子不是原始父母的子女,而且第一代子女永遠不會等待他們,所以產出的順序是不確定的。另外,您需要將waitpid從j循環中取出,並且不要執行它,直到所有孩子都被分出爲止。

+0

你所說的 「孫子」 是什麼意思?我需要父母分娩n個孩子(在這種情況下是3),等待他們,我沒有做任何孫子... – PoweredByOrange

+0

你不打算有孫子,但你正在做他們。第一個孩子打印「孩子%d打印:%d \ n」,然後轉到j循環的頂部並調用fork。 –

+0

哦,那麼我怎麼能沒有創造孫子的循環?! – PoweredByOrange

相關問題