Ram Ram - 1 year ago 68
Bash Question

How to wait on all child (and grandchild etc) process spawned by a script


Users provide me their custom scripts to run. These scripts can be of any sort like scripts to start multiple GUI programs, backend services. I have no control over how the scripts are written. These scripts can be of blocking type i.e. execution waits till all the child processes (programs that are run sequentially) exit

#exaple of blocking script
echo "START"
echo "DONE"

or non blocking type i.e. ones that fork child process in the background and exit something like

#example of non-blocking script
echo "START"
first_program &
second_program &
echo "DONE"

What am I trying to achieve?

User provided scripts can be of any of the above two types or mix of both. My job is to run the script and wait till all the processes started by it exit and then shutdown the node. If its of blocking type, case is plain simple i.e. get the PID of script execution process and wait till ps -ef|grep -ef PID has no more entries. Non-blocking scripts are the ones giving me trouble

Is there a way I can get list of PIDs of all the child process spawned by execution of a script? Any pointers or hints will be highly appreciated

Answer Source

You can use wait to wait for all the background processes started by userscript to complete. Since wait only works on children of the current shell, you'll need to source their script instead of running it as a separate process.

( source userscript; wait )

Sourcing the script in an explicit subshell should simulate starting a new process closely enough. If not, you can also background the subshell, which forces a new process to be started, then wait for it to complete.

( source userscript; wait ) & wait
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download