Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c - getpid and getppid return two different values

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
",id);
    if ( id == 0 )
    {
    printf ( "Child : Hello I am the child process
");
    printf ( "Child : Child’s PID: %d
", getpid());
    printf ( "Child : Parent’s PID: %d
", getppid());
    }
    else
    {
    printf ( "Parent : Hello I am the parent process
" ) ;
    printf ( "Parent : Parent’s PID: %d
", getpid());
    printf ( "Parent : Child’s PID: %d
", 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Process ID 1 is usually the init process primarily 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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...