1

How do find the total number of child processes (recursively) spawned by a script?

For profiling purposes, it is sometimes important to count the generated sub-processes of command, script, etc.

What I tried?

  • ps based solutions -- but it just presents the current running processes.
  • using the next pid number (this is my best solution)

example:

ps | awk '/ ps$/{print $1}'
27159
$ for a in {1..100} ; do date > /dev/null; done  ## 100 processes
$ ps | awk '/ ps$/{print $1-2}'
27259

(27259-27159=100) but the next pid number is reseted and suffers the interference of other tasks.

3
> strace -c -f -e trace=fork,vfork,clone,execve,execl bash -c 'ls -ld /etc;sleep 1'
Process 15683 attached
drwxr-xr-x 1 root root 5540 10. Jan 02:08 /etc
Process 15684 attached
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         2           clone
  0.00    0.000000           0         3           execve
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000                     5           total

> strace -c -f -e trace=fork,clone,execve bash -c '(foo=bar;ls -ld /etc);sleep 1'
Process 15730 attached
Process 15731 attached
drwxr-xr-x 1 root root 5540 10. Jan 02:08 /etc
Process 15732 attached
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         3           clone
  0.00    0.000000           0         3           execve
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000                     6           total
| improve this answer | |
  • This is what I was looking for. Thank you very much! (in my fedora20 machine I had to remove "execl" but I was expecting minor differences between Unix variants) – JJoao Jan 11 '15 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.