C语言 getpid 和 getppid 返回两个不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15183427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getpid and getppid return two different values
提问by Assasins
When I run the code below
当我运行下面的代码时
#include <stdio.h>
#include <sys/types.h>
//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);
}
}
My output is
我的输出是
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
How can the parent's PID(20172) differ from the child's parent's ID (1)? Shouldn't those two be equal?
父母的 PID(20172) 与孩子的父母 ID (1) 有何不同?这两个不应该是平等的吗?
回答by Hymanson
What's happening is that the parent is terminating before the child runs. this leaves the child as an orphan and it gets adopted by the root process with PID of 1. If you put a delay or read data from stdin rather than letting the parent terminate you'll see the result you expect.
发生的事情是父级在子级运行之前终止。这使孩子成为孤儿,它被 PID 为 1 的根进程采用。如果您延迟或从标准输入读取数据而不是让父进程终止,您将看到您期望的结果。
Process ID 1 is usually the init processprimarily responsible for starting and shutting down the system. The init (short for initialization) is a daemon process that is the direct or indirect ancestor of all other processes. wiki link for init
进程ID 1 通常是主要负责启动和关闭系统的 init 进程。init(初始化的缩写)是一个守护进程,它是所有其他进程的直接或间接祖先。init 的 wiki 链接
As user314104 points out the wait() and waitpid() functions are designed to allow a parent process to suspend itself until the state of a child process changes. So a call to wait() in the parent branch of your if statement would cause the parent to wait for the child to terminate.
正如 user314104 指出的那样,wait() 和 waitpid() 函数旨在允许父进程挂起自己,直到子进程的状态发生变化。因此,在 if 语句的父分支中调用 wait() 会导致父级等待子级终止。
回答by Stone.Carton
Because the parent process runs out and released, its child process became an orphan, The init (short for initialization)whose pid is 1 received the orphan process.
由于父进程用完释放,其子进程成为孤儿进程,pid为1的init(initialization的缩写)接收到孤儿进程。

