makeuplover123
makeuplover123

Reputation: 49

Why does the child process think the parent's process id is 1?

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

int main ( void ) {
    int pid, fpid, ppid;

    fpid = fork();

    printf ("fpid is is %d\n", fpid);
    sleep(5);

    if (fpid > 0) {
        pid = getpid();
        ppid = getppid();
        printf ("\nThis is Parent. My pid %d. My parent's pid %d\n", pid, ppid);
    } else if (fpid == 0) {
        sleep(1);
        pid = getpid();
        ppid = getppid();
        printf ("\nThis is Child. My pid %d. My parent'a pid %d\n", pid, ppid);
    }
}

I think when the parent process ID is 1 it means that the parent process has been terminated, so the child process gets re-parented to 1 (init, the first process). Is there any reason why the parent process would be terminated?

Upvotes: 3

Views: 4389

Answers (2)

P.P
P.P

Reputation: 121377

Parent process doesn't wait (by means of wait(2)) for the child process to complete. So, if parent exits before the child (it becomes an orphan process), then child process will be re-parented (adopted) to init process whose process ID is usually 1. Thus the child process says its parent process ID is 1.

Note that the init process' ID isn't necessarily 1 on all systems. POSIX doesn't mandate any such thing.

Upvotes: 5

Petr Skocik
Petr Skocik

Reputation: 60058

Because the child sleeps, by the time it calls getppid(), its parent will have likely died and the child will have been reparented to the init process (pid == 1).

Upvotes: 3

Related Questions