我有以下代码,我试图通过分叉创建子进程。我希望制作 3 个子流程。但是,当我运行代码时,我似乎得到了更多,可能是因为子进程分叉了孙子进程。我在这里错过了什么,我该如何防止这种情况。
代码:
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