分叉和等待

Forking and Waiting

本文关键字:等待 分叉      更新时间:2023-10-16

我正在尝试通过分叉创建进程的粉丝。我希望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)

您应该等到所有孩子完成按照代码的任务完成。

   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");