Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically getting list of child processes of a given PID

I'd like to get a list of all the immediate children of a given PID. I'm OK with using /proc but /proc/<PID>/task/<PID>/children is NOT precise and may return inaccurate results (see section 3.7 here). I'd like a more reliable method of doing this.

I'd prefer not using a wrapper around a shell command.

like image 448
Coder Avatar asked Aug 17 '16 18:08

Coder


People also ask

How do you find the PID of all child processes?

Using the /proc File System It contains information about the kernel, system, and processes. We can find the PIDs of the child processes of a parent process in the children files located in the /proc/[pid]/task/[tid] directories.

What is PID of child process?

The child process has a unique process ID (PID) that does not match any active process group ID. The child has a different parent process ID, that is, the process ID of the process that called fork(). The child has its own copy of the parent's file descriptors.

Is PID 0 the child process?

The if (PID == 0) evaluates the return value. If PID is equal to zero then printf() is executed in the child process, but not in the parent process. The else part of the condition is executed in the parent process and the child process but only the parent process will execute the else part of the condition.


1 Answers

Why not use psutils?

Here is an example where I kill all the children.

def infanticide(pid):
    try:
      parent = psutil.Process(pid)
    except psutil.NoSuchProcess:
      return
    children = parent.children(recursive=True)
    for p in children:
        os.kill(p.pid, signal.SIGKILL)
like image 127
Ian A. Mason Avatar answered Oct 06 '22 13:10

Ian A. Mason