2014-01-20 123 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