# $! - ID of Background job

# The previous example with $$ requires the process to create a special
# filename. This is not necessary if your script launched the other script. This
# information is returned in the "$!" variable.

# It indicates the process ID of the process executed with the ampersand, which
# may be called an asynchronous, or background process.

## Here is the way to start a background process, do something else, and wait
# for the background job to finish:

    #!/bin/sh
    newscript &
    trap "kill -TERM $!" 0 1 2 15
    # do something else
    wait $!

# I used the numbers instead of the names of the signals. I used double quotes,
# so that the variable $! is evaluated properly. I also used the wait command,
# which causes the shell to sleep until that process is finished.

# This script will run two shell processes at the same time, yet if the user
# presses control-C, both processes die. Most of the time, shell programmers
# don't bother with this.
# However, if you are running several processes, and one never terminates (like
# a "tail -f)" then this sort of control is required. Another use is to make
# sure a script doesn't run for a long time.
# # You can start a command in the background, and sleep a fixed about of
# time. If the background process doesn't finish by then, kill it:

    #!/bin/sh
    newscript &
    sleep 10
    kill -TERM $!

# The $! variable is only changed when a job is executed with a "&" at the end.

# The wait command does not need an argument. If executed with no arguments, it
# waits for all processes to be finished. You can launch several jobs at once
# using

    #!/bin/sh
    job1 &
    pid=$!
    job2 &
    pid="$pid $!"
    job3 &
    pid="$pid $!"
    trap "kill -15 $pid" 0 1 2 15
    wait
