[英]How to print the child process with their name and pid once under the last child fork()
我正在學習如何使用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
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++;
}
x
要么為0,要么為0。 如果x
為零,則從fork
調用返回的任何進程都不會產生輸出。 如果x
不為零,則兩個進程都將產生輸出。 因此,您的預期輸出似乎是不可能的。 這些輸出線中的每條線如何運行一次?
推測x
為零。 因此,這兩個過程都產生了輸出。 不同的“子級A”值表明,其中一個來自父級,另一個來自子級。
請注意您的最后一個叉子相對於母帶的位置。 如果您會注意到,子A的PID每次打印都不同,而其他兩個相同。 如果是子代,則PID將為0;如果是父代,則PID將為其他值。 由於孩子A打印兩種不同的東西,因此在孩子和父母中都發生了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.