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?
So there are total eight processes (new child processes and one original process).
Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort.
Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.
Command pstree PID can show all subprocess information of the process specified by PID .
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With