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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With