Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all child processes?

Tags:

c

linux

process

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?

like image 526
c4757p Avatar asked Jun 17 '09 21:06

c4757p


People also ask

How many child processes are there?

So there are total eight processes (new child processes and one original process).

How do I find PID of all processes?

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.

Where is parent and child process ID in Linux?

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.

How do I find subprocess in Linux?

Command pstree PID can show all subprocess information of the process specified by PID .


3 Answers

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.

like image 99
Alex Brown Avatar answered Oct 22 '22 02:10

Alex Brown


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 reallocing 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.

like image 5
Chas. Owens Avatar answered Oct 22 '22 00:10

Chas. Owens


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;
}


like image 5
RC. Avatar answered Oct 22 '22 01:10

RC.