user5162957
user5162957

Reputation:

Unix fork parent id inconsistent

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char * argv[]) {
    printf("I am parent! My id: %d\n", (int)getpid());

    pid_t childPIDorZero = fork();

    if (childPIDorZero == -1) {
        perror("fork() error");
        exit(-1);
    }

    if (childPIDorZero == 0) {
        printf("Success. ID: %d, Parent ID: %d\n", (int)getpid(), (int)getppid());
    }

    return 0;
}

1-Result:

enter image description here

2-Result:

enter image description here

I don't understand this situtaion. Result 1 is true but Result 2 false but I didn't do any changes. Why are the parent ID results different?

Upvotes: 2

Views: 82

Answers (1)

rici
rici

Reputation: 241901

Because the parent never waits for the child to finish (see man waitpid).

As a result, the parent could terminate before the child even starts to execute, in which case the child will be reparented.

The possibly interesting feature of the experiment is that the pid of the new parent is 919, and not 1 as would be expected. (As explained in the Wikipedia article, child processes without parents are given to the init process, which is pid 1.) However, Linux has a facility which allows a process to become a "reaper" of descendant processes, and Ubuntu enables this feature to give each user their own init process. See the "User Session Mode" section in man 5 init, if you are running a system with upstart.

Upvotes: 6

Related Questions