Posts Tagged ‘wait’

Bash: parallel processes

May 9th, 2011 2 comments

Sometimes there is a need for spawning multiple sub processes in a shell script and do something after ALL of them have finished. The Bash has nice little features to do this very easily.

Here is an example:

./process_1 &     # fork first sub process
PID_1=$!          # get PID of first sub process
./process_2 &     # fork second sub process
PID_2=$!          # get PID of second sub process some other work...

wait  ${PID_1}     # stop execution until first process has finished
wait  ${PID_2}     # stop execution until second process has finished

#...all work is done...

exit 0

With the ampersand (&) one can fork sub processes running independent from the parent process.

To avoid busy waiting we want to stop execution of the parent script until the child has finished. So we don’t use an infinite loop with a check and a sleep or something like that, but a function called wait together with the childs’ Process ID.

The PID of a created process can be received by reading $! right after the fork. As far as I know this is mostly bash functionality and maybe is not POSIX! (correct me if I’m wrong)

Categories: bashism, software Tags: , ,