Bash – Finding number of child processes of a particular process

bashprocess

I have a Python script that spawns a few subprocesses but never more than n at a time.

I want to write a shell script to confirm that it has no more than n subprocesses at any given time, but also that generally it has n processes running.

If I have the PID of the Python program inside a shell script, how do I check the number of subprocesses that that PID currently has? E.g.

python script.py &
pid=$!
while true
do
    # do something that prints number of subprocesses of
    # the process $pid to stdout
    sleep 1
done

Best Answer

ps -eo ppid= | grep -Fwc $pid

If your grep does not support -w:

ps -eo ppid= | tr -d '[:blank:]' | grep -Fxc $pid

or

ps -eo ppid= | awk '$1==ppid {++i} END {print i+0}' ppid=$pid

or (clobbering the positional parameters)

set $(ps -eo ppid=); echo $#

Note that this is not atomic, so the count may be wrong if some processes die and others get spawned in the short span of time it takes to gather the data.

Related Question