防止大孩子在C中分叉

Zah*_*tar 0 c fork grandchild

我有以下代码,我正在尝试通过分叉创建子进程.我希望确实有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);    
    } 
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

不要做第二次fork通话,因为它会创建一个新的孩子.第一个就足够了:

for (j = 0; j < 3; ++j)
{
    pid_t pid = fork();
    if (pid == 0)
    {
        printf("In child (j = %d)\n", j);
        exit(0);
    }
    else if (pid > 0)
    {
        printf("In parent (j = %d)\n", j);
    }
}
Run Code Online (Sandbox Code Playgroud)

将打印"In child"三次,j等于0,12.父印刷也是如此.

在您的真实代码中,您应该检查错误.