#include <stdio.h>
int main(void)
{
fork();
fork();
printf("ppid %d pid %d\n", getppid(), getpid());
return 0;
}
The above code sometimes prints
$ ./a.out
ppid 3389 pid 3883
ppid 3883 pid 3885
ppid 1 pid 3884
ppid 3884 pid 3886
Why is process 3884's ppid 1? Doesn't it supposed to be 3883?
ppid 1 indicates that the process is child of the process with pid 1 or the init process. pid = X ppid = 1. or. processes that have been adopted by the process 1 ( init ) It is found that most of the ppid is lower than pid of the same process by 1.
To determine the parent process of a specific process, we use the ps command. The output only contain the parent process ID itself. Using the output from the ps command we can determine the name of the process.
PPID stands for Parent Process ID. In Linux systems, A parent process ID is always assigned to every process ID. It tells us which process started a particular process. Therefore, the PPID value of 0 for the init process indicates that the init process has no parent.
RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
I'd guess the parent process had already completed running and exited by the time the third child checked for the parent's PID. That would have caused the child to be re-parented under init
, which has process ID 1.
Taken from:
http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fapis%2Fgetppid.htm
"The value returned by getppid() is the process ID of the parent process for the calling process. A process ID value of 1 indicates that there is no parent process associated with the calling process."
That printf instruction was executed within the parent process, so it returned 1 because it does not have a parent process. It's perfectly normal that this was the 3rd line to be printed, since the fork run its process concurrently and no particular order is guarantied.
To build upon Jamey's answer, when a process finishes before the child's execution and exits, the child becomes an orphan i.e. orphan process so the kernel maps that orphan to the init process.
Using wait() makes sure that the parent waits until the child has finished execution.
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