【发布时间】:2019-03-27 18:51:42
【问题描述】:
我正在学习如何使用 C++ fork() 方法在 Linux 中生成进程。当我尝试用我创建的 ChildA、B、C 打印出他们的 pid 时。它打印了两次。如果我只希望它们打印一次,我该如何更改代码。
我试图在打印输出命令下进行计数。当它打印一次时,它应该停止并且不再打印。
child_C=fork();
if(Child_C==0){
//do some function here;
}else{
child_B=fork();
if(Child_B==0){
//do some function here;
}else{
child_A=fork();
if(x==0){
cout<<"i am child A" << child_A << "\n";
cout<<"i am child B" << child_B << "\n";
cout<<"i am child C" << child_C << "\n";
x++;
}
if(Child_A==0){
//do some function here;
}else{
//do some function here;
}
}
}
我期望输出:
i am child A 123
i am child B 234
i am child C 345
但它会打印出来:
i am child A 123
i am child B 234
i am child C 345
i am child A 0
i am child B 234
i am child C 345
【问题讨论】: