Text-only Table of Contents (frame/ no frame)
(26) Coprocesses Previous Top Next

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.
command &
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).

ksh coprocesses

Coprocesses are a way of starting a separate process which runs asychronously, but has stdin/stdout connected to the parent script via pipes.
command |&
Start a coprocess with a 2-way pipe to it
read -p var
Read from the pipe to the coprocess, instead of standard input
print -p args
Write to the pipe connected to the coprocess, instead of standard output
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.
exec <&p
The input from the coprocess is moved to standard input
exec >&p
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.

Previous Top Next

coprocesses.src  last modified Mar 11, 2005 Introduction Table of Contents
(frame/no frame)
(single file)
© Dartmouth College