在shell中执行fork命令以打印进程ID

2 c unix shell fork process-reaper

我试图pid在运行fork()命令后打印进程.这是我的代码 -

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的答案 -

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 
Run Code Online (Sandbox Code Playgroud)

为什么父母不在第二行.2420为什么我得到我1910怎么能得到这个价值?

Bar*_*mar 7

父母在孩子执行printf呼叫之前退出.当父母退出时,孩子会得到一个新的父母.默认情况下,这是init进程,PID 1.但是最新版本的Unix增加了进程将自己声明为"subreaper"的能力,该子进程继承了所有孤立的子进程.PID 1910显然是您系统的辅助设备.有关此内容的详细信息,请参阅https://unix.stackexchange.com/a/177361/61098.

把一个wait()呼叫父进程使其等待孩子退出后再继续.

#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;
}
Run Code Online (Sandbox Code Playgroud)