通过fork创建进程和子进程:无法解释的行为

3
我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
for(int i=0;i<3;i++)
{
int cpid=fork();
if(cpid==0)
    printf("I am a child with id %d, and my parent is %d\n",getpid(),getppid());
else
    printf("I am a parent with id %d\n",getpid());
}
}

我正在尝试形成一个进程树。输出结果如下:

I am a parent with id 9494 
I am a parent with id 9494 
I am a child with id 9495, and my parent is 9494
I am a parent with id 9494 
I am a child with id 9496, and my parent is 9494
I am a parent with id 9495 
I am a parent with id 9496 
I am a parent with id 9495 
I am a child with id 9498, and my parent is 9495
I am a parent with id 9498 
I am a child with id 9499, and my parent is 3004
I am a child with id 9497, and my parent is 3004
I am a child with id 9500, and my parent is 3004
I am a child with id 9501, and my parent is 3004

我无法找出进程ID为3004的进程来自哪里。由于此代码,总共创建了多少个进程?最终的进程树是什么样子的?我是初学者。

2个回答

2

我将帮助解决进程3004的神秘问题。其余部分应该相对容易自行解决(你可能需要在第二个printf()中添加cpid以帮助解决问题)。

I am a child with id 9499, and my parent is 3004

这里发生的情况是,在进程 9499 调用 getppid() 之前,其原始父进程已经死亡。当一个进程的父进程死亡时,该进程会被重新分配父进程。在您的情况下,新父进程的 pid 是 3004。此进程不是由您的程序创建的进程树的一部分(它可能位于整个进程树的上方某处),因此您看不到它的“我是带有 id 的父进程”信息。
这里有一些相关阅读:进程重新分配父进程:控制新父进程

1

尝试这段代码。

这段代码的输出将会对你解释更多的事情。一些进程在它们的父进程死亡后,print它们各自的printf函数。这些进程(孤儿进程)被其他进程所接管。这可能是printf函数打印出奇特pid的原因。同时,进程创建和它们各自pid的打印之间存在竞争条件,可以在下面代码的输出中看到。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    printf("Main\n");
    for(int i=0;i<3;i++) {
        printf("Loop index - %d and pid is - %d\n", i, getpid());
        int cpid=fork();
        if(cpid==0) 
             printf("I am a child with id %d, and my parent is %d with loop index - %d\n",getpid(),getppid(), i);
        else
              printf("I am a parent with id %d and with loop index - %d\n",getpid(), i);
    }
    printf("Terminated - %d\n", getpid());
    return 0;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接