How do find the granchild pid in C?

Viewed 39

I am trying to code a toy process manager and was wondering how do I find the grandchild pids when one of my children pids dies. I.e. how to deal with the "Readiness protocol".

systemd has the "Type=forking" option, which as far as I understand, waits for the forked pid to die and then assumes that one of the forked pid's children is the actual "daemon" to monitor.

My code so far is as following, but I am missing the XXX

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

int
main (int argc, const char *argv[])
{
    printf("sup stared\n");
    int pid;

    prctl(PR_SET_CHILD_SUBREAPER);

    pid = fork();
    if (pid == 0) {
        setpgid(0, 0);
        printf("service started, pid: %d, pgid: %d\n",
               getpid(), getpgid(0));
        int dpid;
        dpid = fork();
        if (dpid == 0) {
            printf("daemon started, pid: %d, pgid: %d\n",
                   getpid(), getpgid(0));
            while (1);
        }
        printf("service exiting\n");
        return 0;
    } else {
        printf("service pid: %d\n", pid);
        int rc;
        rc = waitpid(pid, NULL, 0);
        printf("service exited? %d\n", rc);
        
        int dpid;
        dpid = XXcX();

        printf("daemon, %d\n", dpid);
    }

   return 0;
}
0 Answers
Related