coperating-systemfreebsd

FreeBSD - Find child processes from parent pid in C


This question is specifically for freeBSD.

Is there an OS function I can call in C to get child processes from a parent's process id (pid)?

I'm looking for exactly what pgrep -P <PID> does.

I've come across getting kinfo_proc but there doesn't seem to be any mention of where any children's pids are stored.

Online all I can see is iterating over every single process to find if that process's parent pid is the one I'm searching for.

This seems wildly inefficient and I was wondering if there was any function/file I could use to get child processes from a parent by pid.

Please don't include a solution with procfs as this program is intended to run on various instances so setting up something like procfs specifically for my system won't work.


Solution

  • https://github.com/freebsd/freebsd-src/blob/main/bin/pkill/pkill.c

    
        /*
         * Retrieve the list of running processes from the kernel.
         */
        kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
        if (kd == NULL)
            errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
    /*
         * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
         * just want processes and not individual kernel threads.
         */
        if (pidfromfile >= 0)
            plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
        else
            plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
        if (plist == NULL) {
            errx(STATUS_ERROR, "Cannot get process list (%s)",
                kvm_geterr(kd));
        }