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