How do find the number of child processes of a bash script, from within the script itself?
Use the procfs : count the number of directories in /proc/[mypid]/task and you have the number of child processes started.
There is always only one parent process of these processes and remaining will be child processes.
There is 3 processes.
Fork #4 is executed by half of the processes created by fork #3 (so, four of them). This creates four additional processes. You now have twelve processes.
To obtain the PID of the bash script you can use variable $$
.
Then, to obtain its children, you can run:
bash_pid=$$
children=`ps -eo ppid | grep -w $bash_pid`
ps
will return the list of parent PIDs. Then grep
filters all the processes not related to the bash script's children. In order to get the number of children you can do:
num_children=`echo $children | wc -w`
Actually the number you will get will be off by 1, since ps
will be a child of the bash script too. If you do not want to count the execution of ps
as a child, then you can just fix that with:
let num_children=num_children-1
UPDATE: In order to avoid calling grep
, the following syntax might be used (if supported by the installed version of ps
):
num_children=`ps --no-headers -o pid --ppid=$$ | wc -w`
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