C - 从单亲分叉

C - Forking from a single parent

我正在尝试编写一个小程序,从单亲派生进程。目前,我的代码执行了几次,但随后子进程创建了更多我想消除的子进程。

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c > 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(i), getpid(i)); 
        }
    }
}

我不确定如何修改它,以便 fork 仅从父级 fork。

编辑:感谢您的帮助,得到了解决方案:

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c > 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(i), getpid(i)); 
        }

        else {
            exit(0); 
        } 
    } 
}

child 进程不进入 if 块的任何部分,只是循环回到 for 循环的顶部,创建更多 children。此外,if (n > 0) 块为 parent 获取 运行,而不是 child,因为 fork returns 0 到 parent child 的 pid 到 parent.

if (n > 0)改为if (n == 0),并在块的底部调用exit()以防止child继续。此外,getpid()getppid() 不接受任何参数。

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c == 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(), getpid()); 
            exit(0);    // <-- here
        }
    } 
}

发布的代码中没有任何内容可以识别 child (0 == pid)

所以 child 命中(并跳过)两个 'if' 语句。

点击循环结束,

分支回到循环的顶部,调用 fork()....等。

建议:添加

elseif( 0 == pid ) 
{ // then child ...   
    exit( EXIT_SUCCESS );
}