1

I have been reading the book "Understanding the Linux Kernel" and it has a chapter in it that claims if the parent process dies before the child process, the child's parent will be set to the init process with the PID of 1. But when I actually test it out, I find out it's set to the process with the name systemd and its PID is 1702(which is probably random, and doesnt seem to be constant).

The code I used to test this is:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int 

main() {

    pid_t PID;
    pid_t parentPID;
    pid_t initPID;
    initPID = fork();

    if (initPID < 0) { exit(0); }
    if (initPID == 0) {
            PID = getpid();
            parentPID = getppid();
            printf("Child PID: %d, Parent PID: %d\n", PID, parentPID);
    }
    if (initPID != 0) {
            PID = getpid();
            parentPID = getppid();
            printf("Parent PID: %d, Parent of Parent PID: %d\n", PID, parentPID);
            exit(0);
    }

    PID = getpid();
    parentPID = getppid();
    printf("After death - Child PID: %d, Parent PID: %d\n", PID, parentPID);

}

I compile and run the program, and the output I get is the following:

[$user]understand the kernel$ gcc child_states.c -o test
[$user]understand the kernel$ ./test 
Parent PID: 7245, Parent of Parent PID: 3698
Child PID: 7246, Parent PID: 7245
After death - Child PID: 7246, Parent PID: 1702
[$user]understand the kernel$ ps -ej | grep 1702
 1702  1702  1702 ?        00:00:00 systemd
 1703  1702  1702 ?        00:00:00 (sd-pam)
[$user]understand the kernel$
Guy Sudai
  • 111
  • 1
    Yes, linux has so-called "sub-reapers", look for PR_SET_CHILD_SUBREAPER in the prctl(2) manpage. I cannot test it now, but I remember that that was used by systemd. –  Dec 12 '19 at 22:28
  • Hmm, I get it. so instead of using init it uses those so-called sub-reapers? It makes sense, If I look at the parents I get: init -> systemd -> gnome-terminal -> bash -> executable. Cool thanks! – Guy Sudai Dec 12 '19 at 22:33
  • Just tried to remove systemd from that chain by killing it and I accidentally crashed my virtualbox haha – Guy Sudai Dec 12 '19 at 22:36
  • 1
    Dupe https://unix.stackexchange.com/questions/250153/what-is-a-subreaper-process and https://unix.stackexchange.com/questions/149319/new-parent-process-when-the-parent-process-dies/ – dave_thompson_085 Dec 13 '19 at 05:45

1 Answers1

0

AFAIK systemd uses cgroups to prevent child processes to escape and get attached to PID1 like it used to be with old init systems. And one can keep traceability like that.

AIDoubt
  • 131