shell 中的 fork 命令打印进程 ID

Fork command in shell to print process ids

我正在尝试在 运行 fork() 命令之后打印进程的 pid。这是我的代码-

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int pid;
    pid=fork();
    if(pid==0)
        printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
    else
        printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
    return 0;
}

这就是我得到的答案-

I am the parent.My pid is 2420. My childs pid is 3601 
I am the child.My pid is 3601 .My parents pid is 1910 

为什么第 2 行的 parents id 不是 2420。为什么我得到 1910 我怎样才能得到这个值?

parent 在 child 执行其 printf 调用之前退出。当 parent 退出时,child 得到一个新的 parent。默认情况下,这是 init 进程,PID 1。但是最近的 Unix 版本增加了进程声明自己为 "subreaper" 的能力,它继承了所有孤立的 children。 PID 1910 是 apparently 系统上的 subreaper。有关详细信息,请参阅 https://unix.stackexchange.com/a/177361/61098

在 parent 进程中放置一个 wait() 调用,使其在继续之前等待 child 退出。

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int pid;
    pid=fork();
    if(pid==0) {
        printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
    } else {
        printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
        wait(NULL);
    }
    return 0;
}