【问题标题】:Forking and Waiting分叉和等待
【发布时间】:2014-01-20 12:24:47
【问题描述】:

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

【问题讨论】:

标签: c++ fork wait pid


【解决方案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");

【讨论】:

  • 是的,我按照@Developer SuRu 的建议,在括号中添加了等待命令,一切正常。因为我不认为您可以选择最佳答案的评论,所以我会选择您的评论,因为它基本上包含相同的想法。
猜你喜欢
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多