Running programs in order
You may wish a program to run only when another has completed.
If a large program (myprogram , say) is to be run, and
you require to be mailed a message when it has finished, you could
create a file containing
sh myprogram
echo "Program completed" | mailx chris
and then run the commands from that file in the background using
sh and & . This is not always
convenient, and once myprogram has begun to execute
you cannot go back and edit the file. Another possibility is to use
command wait . In order to do this, you require the PID
of the command you wish to wait for. As an example, create a file
called myprogram containing
sleep 200
date
Run this in the background:
$ sh myprogram &
[1]+ 14523
and you will be informed of the PID of the process running
myprogram , in this case 14523 . Now,
create another file (say notify ):
$ cat >notify
wait 14523
echo "Program completed"
ctrl-D
The command wait is similar to sleep ,
except that instead of waiting a specified number of seconds, it
waits until a process (which is its argument) terminates. If we now
run notify in the background,
$ sh notify &
then as soon as myprogram has finished,
notify will write Program completed on
your terminal. There are restrictions on the use of
wait - you can only wait for a process to complete if
that process has been spawned from the current shell. Thus
you cannot wait for someone else's process to complete. If you call
wait with no arguments, it will wait for all child
processes to terminate - therefore, if you are running many jobs in
the background wait will not complete until each of
them has finished. Normally you would use wait with a
PID as argument.
|