getpid和getppid返回两个不同的值

当我运行下面的代码时

#include  #include  //int i=0; int main(){ int id ; id = fork() ; printf("id value : %d\n",id); if ( id == 0 ) { printf ( "Child : Hello I am the child process\n"); printf ( "Child : Child's PID: %d\n", getpid()); printf ( "Child : Parent's PID: %d\n", getppid()); } else { printf ( "Parent : Hello I am the parent process\n" ) ; printf ( "Parent : Parent's PID: %d\n", getpid()); printf ( "Parent : Child's PID: %d\n", id); } } 

我的输出是

 id value : 20173 Parent : Hello I am the parent process Parent : Parent's PID: 20172 Parent : Child's PID: 20173 id value : 0 Child : Hello I am the child process Child : Child's PID: 20173 Child : Parent's PID: 1 

父母的PID(20172)如何与孩子的父母的身份证(1)不同? 这两者不应该相等吗?

发生的事情是父母在孩子跑步前终止。 这使得孩子成为一个孤儿,并且它被PID为1的根进程所采用。如果你设置延迟或从stdin读取数据而不是让父母终止你将看到你期望的结果。

进程ID 1通常是主要负责启动和关闭系统的init进程 。 init(初始化的简称)是一个守护进程,它是所有其他进程的直接或间接祖先。 用于init的wiki链接

正如user314104指出的那样,wait()和waitpid()函数被设计为允许父进程暂停,直到子进程的状态发生变化。 因此,在if语句的父分支中调用wait()会导致父进程等待子进程终止。

由于父进程耗尽并释放,其子进程成为孤儿,其pid为1的init(初始化的简称)收到了孤立进程。