2014-01-20 38 views
0

我想通過分叉創建一個進程的粉絲。我想要1個進程作爲粉絲的基礎,並且所有其他進程都要從基礎派生(所有進程都有相同的父進程,P1是P2,P3,P4,...的父進程)。分叉和等待

我已經得到了這個部分就好了。我真正的問題在於等待父母程序(我認爲)完成製作孩子。這裏是我下面的代碼:

//Create fan of processes 
#include <iostream> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 

using namespace std; 

int main() 
{ 
    pid_t pid; 
    cout << "Top Parent: " << getpid() << endl; 
    for (int i = 0; i < 9; ++i) { 
    pid = fork(); 
    if (pid) { //parent process 
     continue; 
    } else if (pid == 0) { 
     cout << "Child: (" << getpid() << ") of Parent: (" << getppid() << ")" << endl; 
     break; 
    } else { 
     cout << "fork error" << endl; 
     exit(1); 
    } 
    } 
} 

想我需要在得到輸出的行爲本身的一些幫助,因爲這是它的樣子:

Top Parent: 6576 
Child: (6577) of Parent: (6576) 
Child: (6581) of Parent: (6576) 
Child: (6583) of Parent: (6576) 
Child: (6579) of Parent: (1) 
[[email protected] folder]$ Child: (6585) of Parent: (1) 
Child: (6584) of Parent: (1) 
Child: (6582) of Parent: (1) 
Child: (6580) of Parent: (1) 
Child: (6578) of Parent: (1) 
+0

http://www.amparo.net/ce155/fork-ex.html [GETPID和getppid返回兩個不同的值](的 –

+0

可能重複http://stackoverflow.com/questions/15183427/getpid -and-getppid-returns-two-different-values) – Jackson

+0

謝謝SuRu,正是我需要的。 – FailedFace

回答

1

你應該等到所有的孩子完成他們的任務將以下代碼放在父級方面。

printf("Parent process started.n"); 
     if ((pid = wait(&status)) == -1) 
            /* Wait for child process.  */         */ 
      perror("wait error"); 
     else {      /* Check status.    */ 
      if (WIFSIGNALED(status) != 0) 
       printf("Child process ended because of signal %d.n", 
         WTERMSIG(status)); 
      else if (WIFEXITED(status) != 0) 
       printf("Child process ended normally; status = %d.n", 
         WEXITSTATUS(status)); 
      else 
       printf("Child process did not end normally.n"); 
     } 
     printf("Parent process ended.n"); 
+0

是的,我加入了等待命令到父母,如果括號和一切都很好,遵循@Developer SuRu的建議。因爲我不認爲你可以選擇最佳答案的評論我會選擇你的,因爲它基本上包含了同樣的想法。 – FailedFace