【发布时间】:2026-02-02 16:45:01
【问题描述】:
请检查我的代码,它是一个 C++ 程序,可以生成一个父母的 2 个孩子。用户应输入 num 值以创建流程链。问题是每个父母的孩子 pid 都是一样的,我怎样才能让他们不同?
#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。
标签: c++ operating-system fork