cbashprocessorphan

how to inherit orphan processes instead of systemd


In Operating System Concepts book (Section 3.3.2), it mentioned that by systemd (not by init)it is possible to inherit orphan process by another process instead of systemd.

How can I do that both inside bash (command line mode) and C program?


Solution

  • refer to prctl() in C

    PR_SET_CHILD_SUBREAPER (since Linux 3.4) If arg2 is nonzero, set the "child subreaper" attribute of the calling process; if arg2 is zero, unset the attribute. When a process is marked as a child subreaper, all of the children that it creates, and their descendants, will be marked as having a subreaper. In effect, a subreaper fulfills the role of init(1) for its descendant processes. Upon termination of a process that is orphaned (i.e., its immediate parent has already terminated) and marked as having a subreaper, the nearest still living ancestor subreaper will receive a SIGCHLD signal and be able to wait(2) on the process to discover its termination status.

    Try to use prctl(PR_SET_CHILD_SUBREAPER, 1) call, which will allow it to adopt orphaned processes

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/prctl.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    
    void spawn_orphan() {
        pid_t pid = fork();
        if (pid == 0) {
            printf("Orphan process created with PID: %d\n", getpid());
            sleep(10); // Keep it alive
            _exit(0);
        }
    }
    
    int main() {
        if (prctl(PR_SET_CHILD_SUBREAPER, 1) == -1) {
            perror("prctl");
            exit(1);
        }
    
        spawn_orphan();
    
        int status;
        pid_t orphan_pid;
        while ((orphan_pid = wait(&status)) > 0) {
            printf("Subreaper adopted orphan process PID: %d\n", orphan_pid);
        }
        return 0;
    }