为什么来自孩子的getppid()返回1

use*_*879 10 c linux fork process

我正在运行该程序

#include<stdio.h>
#include <unistd.h>
main()
{
    pid_t pid, ppid;
    printf("Hello World1\n");
    pid=fork();
    if(pid==0)
    {
        printf("I am the child\n");
        printf("The PID of child is %d\n",getpid());
        printf("The PID of parent of child is %d\n",getppid());
    }
    else
    {
        printf("I am the parent\n");
        printf("The PID of parent is %d\n",getpid());
        printf("The PID of parent of parent is %d\n",getppid());        
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是.

$ ./a.out 
Hello World1
I am the parent
The PID of parent is 3071
The PID of parent of parent is 2456
I am the child
The PID of child is 3072
The PID of parent of child is 1
Run Code Online (Sandbox Code Playgroud)

我无法理解这条线

孩子的父母的PID是1

应该是3071?

xle*_*ier 15

因为父进程在孩子要求其父母的pid时完成.

当一个进程完成时,它的所有子进程都被重新分配为init进程的子进程,其pid为1.

尝试wait()在父代码中使用等待子代执行.它应该按预期工作.