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

alk
  • 69,737
  • 10
  • 105
  • 255
  • Please format your code correctly the next time. – Marco Feb 10 '17 at 19:02
  • 1
    It has no reason to stick around, assuming a flat-out guess the remainder of your code you chose *not* to post has no `wait` in the parent process code path to wait for it's child process to finish and gather its status. – WhozCraig Feb 10 '17 at 19:03
  • OT: `fork()` returns a `pid_t`, not an `int`, BTW. Same for `getpid()`and `getppid()`. – alk Feb 10 '17 at 19:06
  • 1
    Your classmate already asked about this: http://stackoverflow.com/questions/42151119/fork-and-parent-child-process-ids/42151383 – John Bollinger Feb 10 '17 at 19:11

2 Answers2

5

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • For recent Linuxes the adopter doesn't even need to the `init` process anymore. See this comment: https://stackoverflow.com/questions/10519842/is-it-possible-to-adopt-a-process#comment47719364_10550076 – alk Feb 10 '17 at 19:13
  • "init" is more of conventional name (historic name from Unix days). Debians call it, for example, use systemd. – P.P Feb 10 '17 at 19:18
  • I am not referring to this. The special, quiet new thing with `PR_SET_CHILD_SUBREAPER` (to be used with `prctl()`) is is that the parent on run-time can decide which process should adopt its child ... :-) – alk Feb 10 '17 at 19:20
  • 1
    While I wasn't referring to that, POSIX says the parent process ID of orphaned process(es) is "implementation defined system process". Which means Linux is free to do that (that you have pointed out - good info. Thanks). – P.P Feb 10 '17 at 19:24
3

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).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142