分叉和等待

时间:2014-01-20 12:24:47

标签: c++ fork wait pid

我试图通过分叉创建流程的粉丝。我想要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)
[remoteuser@server 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)

1 个答案:

答案 0 :(得分: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");