argamanza
argamanza

Reputation: 1142

Process parent ID of child process is different from PID of parent

I'm trying to work with multiple processes in Linux using fork() function in C, this is my code:

p1 = fork();

if(p1 != 0){
    p2 = fork();
}

printf("My PID is %d\n",getpid());
printf("My parent PID is %d\n",getppid());

Now let's assume the parent process ID is 100, and the two child processes (p1, p2) IDs are 101 & 102, and the init process PID will be 0 my expected output is:

My PID is 100
My parent PID is 0

My PID is 101
My parent PID is 100

My PID is 102
My parent PID is 100

Instead i see something different, the two child processes have the same PPID but the first process has a different PID from that. Here is a sample output i got:

My PID is 3383
My parent PID is 3381

My PID is 3387
My parent PID is 1508

My PID is 3386
My parent PID is 1508

My question is, shouldn't the parent PID of the two child processes be 3383? Hope someone can explain how it all works here and what am i doing (or thinking) wrong.

Upvotes: 4

Views: 4904

Answers (2)

Mukesh
Mukesh

Reputation: 83

There is Nothing Wrong with Your Code

Its Just that your parent process exits before the child processes finish hence they become orphan and are adopted by init or any implementation-defined process(1508 in your case).

try puttin wait(); for parent to finish the execution of all the child processes.

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

[Confirmed from the comments]

Your output is timing dependant. If the parent process finishes after the children process, your output will be as expected.

If parent process finishes before the children process, output may be surprising (Before parent does not exist any more, parent id would be different). Once parent process dies (ends), init or some other implementation-defined process(1508 in your case), becomes the new parent of the child(ren). Such children are called orphan process(es).

According to the exit man page from The Single UNIX Specification, Version 2:

The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.

To avoid this, ensure that parent process is alive at the time of fetching parent pid. One way to do this is to add a wait in parent (or all) process before exiting.

Upvotes: 7

Related Questions