我有下面的代碼,我試圖通過分叉創建子流程。我想要完成3個子過程。然而,當我運行代碼時,我似乎越來越多,可能是因爲子進程分叉孫子。我在這裏錯過了什麼,我該如何防止這一點。防止大孩子在C中分叉
代碼:
for(j = 0; j < 3 ; j++){
if((pid = fork()) == 0){ // child process
dosomething();
exit(0); // terminate child process
}
else if((pid = fork()) > 0){
printf("I'm in parent of the client spawn loop\n");
// exit(0);
}
}
輸出:
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
您正在調用fork兩次。 –
是啊,明白了!這對我來說是一種粗心大意!複製粘貼總案例 –