Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this ppid == 1? Am I missing something about fork()?

Tags:

c

fork

#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?

like image 207
zjk Avatar asked Nov 01 '12 03:11

zjk


People also ask

What does PPID 1 mean in Linux?

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.

How do you get PPID of a process in Linux?

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.

What does PPID 0 mean?

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.

What happens when fork returns 0?

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.


3 Answers

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.

like image 142
Jamey Sharp Avatar answered Nov 15 '22 21:11

Jamey Sharp


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.

like image 23
Hernan Velasquez Avatar answered Nov 15 '22 23:11

Hernan Velasquez


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.

like image 27
Shanth K Gaitonde Avatar answered Nov 15 '22 23:11

Shanth K Gaitonde