getpid和getppid返回两个不同的值

时间:2013-03-03 07:25:34

标签: c fork pid

当我运行下面的代码时

#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);
    } 

}

我的输出是

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)不同?这两者不应该相等吗?

2 个答案:

答案 0 :(得分:24)

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

  

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

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

答案 1 :(得分:0)

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

相关问题