In a Linux-based project that I am working on, I need to be able to find all of my child processes. It is not feasible to record every time one is started -- they need to be found after the fact. This needs to be pure C, and I'd like to do it without reading /proc. Does anyone know how to do this?
You could parse a process list (ps -ax?) that included the parent process ID. This could probably be done with a simple shell script.
You could use popen
Something like. (Hopefully the syntax is close enough)
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp = popen("ps -C *YOUR PROGRAM NAME HERE* --format '%P %p'" , "r"); if (fp == NULL) { printf("ERROR!\n"); } char parentID[256]; char processID[256]; while (fscanf(fp, "%s %s", parentID, processID) != EOF) { printf("PID: %s Parent: %s\n", processID, parentID); // Check the parentID to see if it that of your process } pclose(fp); return 1; }
sangretu's answer got me thinking, The source code of the ps command would be a good place to start
It is usually entirely feasible to record child processes every time you start one. conveniently, the parent process is passed the pid value of the child process as the return value of the fork call which creates it.
As the man page says:
pid_t fork(void);
It would help if you could tell us why you think it isn't feasible.
If you want to trace fork events and extract child pids for debugging purposes, there are a number of ways to do that, including:
- Using GDB
- using strace
- Using systemtap
- Using kernel event connectors (not sure what these are exactly)
I find your comment that it is not feasible to record the creation of processes to be odd, but if you really can't (possibly because you don't know how many will be created and don't want to have to keep realloc
ing memory), then I would probably open all of the files that match the glob /proc/[1-9]*/status
and look for the line that says PPid: <num>
where <num>
was my process id.