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$
PR_SET_CHILD_SUBREAPER
in theprctl(2)
manpage. I cannot test it now, but I remember that that was used by systemd. – Dec 12 '19 at 22:28init
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:33systemd
from that chain by killing it and I accidentally crashed my virtualbox haha – Guy Sudai Dec 12 '19 at 22:36