请您检查一下我的代码,它是一个C++程序,用于生成一个父代的2个子代。用户应该输入num值来创建一个过程链。问题是每个家长的孩子pid是一样的,我怎样才能让他们与众不同?使用fork()生成2个孩子的C++
#include<iostream>
#include<sys/types.h>
#include<unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
cout<<"Please enter a number of process "<<endl;
int num;
cin>>num;
int j;
for(j=0; j<num; j++)
{
pid_t pid;
pid = fork();
if(pid < 0)
{
cout<<"Error"<<endl;
exit(1);
} else if (pid > 0) {
cout << "Parent " << getpid() << endl;
exit(0);
}
else {
int i;
for(i = 0; i < 2; i++) {
wait(NULL);
cout << " Child " << getpid() << endl;
}
}
}
return 0;
}
输出是
Parent 27130
Child 27322
Child 27322
Parent 27322
Child 31901
Child 31901
Parent 31901
Child 20453
Child 20453
这是我不清楚预期的输出是什么。 –
@RSahu他希望它只打印一次。他想要查看父级创建的两个子进程的pid。 –