Coprocesses and Background jobs
Scripts can start any number of background jobs (any external command),
which run in parallel with the
parent script, and asynchronously. Processes which require no further interaction
or synchronization (fire and forget) are easy.
Interaction with background jobs is tricky. You can
use signals, pipes, named pipes, or disk files for communication.
- Start command as a background process. Control returns immediately to the shell.
- The special variable
$! contains the process ID of the last background job
that was started. You can save that and examine the process later
ps -p $bgpid) or send it a signal (
kill -HUP $bgpid).
Coprocesses are a way of starting a separate process which
runs asychronously, but has stdin/stdout connected to the parent script via pipes.
Multiple coprocesses can be handled by moving the special file descriptors connected
to the pipes onto standard input and output, and or to explicitly specified file descriptors.
- Start a coprocess with a 2-way pipe to it
- Read from the pipe to the coprocess, instead of standard input
- Write to the pipe connected to the coprocess, instead of standard output
- The input from the coprocess is moved to standard input
- The output from the coprocess is moved to standard output
Example: ex9 display, text
A script wants to save a copy of all output in a file, but also wants a copy
to the screen. This is equivalent to always running the script as
script | tee outfile
Example: ex10 display, text
Start a coprocess to look up usernames in some database.
It is faster to run a single process than to run a separate
lookup for each user.