Waiting for background processes to finish before exiting script

egorulz picture egorulz · Jan 10, 2013 · Viewed 105.3k times · Source

How do I make sure that all my background processes have finished execution before I exit my script (TCL/Bash).

I was thinking of writing all my background process pids to a pidfile. And then at the end pgrep the pidfile to see if any processes are still running before I exit.

Is there some simpler way to do this? And is there a TCL specific way to do this?

Answer

William Pursell picture William Pursell · Jan 10, 2013

If you want to wait for jobs to finish, use wait. This will make the shell wait until all background jobs complete. However, if any of your jobs daemonize themselves, they are no longer children of the shell and wait will have no effect (as far as the shell is concerned, the child is already done. Indeed, when a process daemonizes itself, it does so by terminating and spawning a new process that inherits its role).

#!/bin/sh
{ sleep 5; echo waking up after 5 seconds; } &
{ sleep 1; echo waking up after 1 second; } &
wait
echo all jobs are done!