c - 防止孙子在 C 中 fork

标签 c fork grandchild

我有以下代码,我在其中尝试通过 fork 创建子进程。我希望完成 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

最佳答案

不要执行第二个 fork 调用,因为它会创建一个新的 child 。第一个就够了:

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);
    }
}

将打印 "In child" 三次,其中 j 等于 012。父打印也是如此。

不过,在您的实际代码中,您应该检查错误。

关于c - 防止孙子在 C 中 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18965918/

相关文章:

c - 在 C 中提取子字符串

c - 在我的程序中使用 OpenBSD 的 malloc、realloc 和 free

c - 2路管道通讯。不能从 child 身上花

python - 如何从孙子类调用 super 方法?

c - 为什么我的 for 循环无限运行?

c++ - 需要分析帮助

linux - 按 pid 进行跟踪,包括子进程

c - 如何使用 fork() 来守护独立于其父进程的子进程?

html - 有没有办法在没有 jQuery/javascript 的情况下将元素与其 'grandparent' 对齐?