系统相关
首页 > 系统相关> > 进程分叉创建:无法解释的行为

进程分叉创建:无法解释的行为

作者:互联网

我有以下代码:

#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的进程从哪里来.由于此代码,总共创建了多少个进程?最终的流程树将是什么?我是初学者.

解决方法:

我将帮助解决流程3004的奥秘.其余部分应该可以很容易地自己弄清楚(您可能希望在第二个printf()中添加cpid来解决这个问题).

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

这里发生的是,9499进程的原始父进程在9499有机会调用getppid()之前就已经去世了.当进程的父进程去世时,该进程将被重新父化.在您的情况下,新父级的pid是3004.此进程不是您的程序创建的进程树的一部分(它可能位于整个进程树的上方),因此您看不到“我是父母ID”.

这里是一些相关的阅读:process re-parenting: controlling who is the new parent.

标签:operating-system,parent-child,linux
来源: https://codeday.me/bug/20191118/2026650.html