Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of child processes

Tags:

bash

process

pid

How do find the number of child processes of a bash script, from within the script itself?

like image 436
Adam Matan Avatar asked Jul 18 '12 13:07

Adam Matan


People also ask

How do you find the number of child processes?

Use the procfs : count the number of directories in /proc/[mypid]/task and you have the number of child processes started.

What are the total number of child process remaining?

There is always only one parent process of these processes and remaining will be child processes.

How many child processes are created when executing this program?

There is 3 processes.

How many processes are created by 4 forks?

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.


1 Answers

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`
like image 176
betabandido Avatar answered Sep 30 '22 18:09

betabandido