Phil for Humanity Phil for Humanity
A Guide for the Survival of Humankind and Helping the World, Society, and Yourself.

Selective UNIX Wait

Have you ever wanted to spawn several children processes in UNIX, but only wanted to wait for some of them? Here is how.

First, look at this simple Korn shell script.

command1.exe &
command2.exe &
echo Done 1

The script will first run the command “command1.exe” as a child process, and then run the command “command2.exe” in another child process. Finally, the wait will pause the Korn script until all children process have finished executing or have been terminated. So, “Done 1” will be printed to the screen after both commands (“command1.exe” and “command2.exe”) have completed running.

Now assume that you want to run the same two commands, but you only want to wait on the first command and NOT wait on the second command. Here is how to do it.

command1.exe &
(command2.exe &) &
echo Done 2

This second script will first run the command “command1.exe” as a child process. Next, the script creates a second child process and runs “commands2.exe &” in it. This second child process will start its own child process that will run just “commands2.exe” in it. The second child process will exit, while its' child process is still running. Next, the “wait” command will only wait until the first child process finishes running before allowing the echo command to execute. This works because the wait command will only wait on child processes to be completed and does not wait on any grandchild processes.

Now, if you wanted to wait on grandchild processes, then you will have to manually recreate some type of test, signal, or semaphore like this:

( touch filename.txt ; ( command.exe; rm filename.txt) &) &

This will create a temporary file, run the command, and then delete the temporary file when done. So, you just have to continuous test for when the file no longer exists, and you are done waiting on this grandchild process.

by Phil for Humanity
on 03/29/2011

Related Articles
 » How to Fork a Child Process and Wait in Perl
 » UNIX Support: Analyzing and Improving System Loads
 » Waiting for Child Process in Perl