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)
http://www.amparo.net/ce155/fork-ex.html [GETPID和getppid返回两个不同的值](的 –
可能重复http://stackoverflow.com/questions/15183427/getpid -and-getppid-returns-two-different-values) – Jackson
谢谢SuRu,正是我需要的。 – FailedFace