I have two programs piped in my bash script:
program1 | program2
Instead of using an anonymous pipe, use a named pipe that gives you more control over each end.
mkfifo p program1 > p & p1_pid=$! program2 < p kill "$p1_pid"
In this snippet, we create a named pipe called
p, then run
program1 in the background with its standard output redirected to
p1_pid stores the process ID of
program1 for later use. Note that
program1 is started, but immediately blocks until something opens p
for eading. We runprogram2
with its standard input redirected fromp`, then block while it runs.
program2 exits for whatever reason, the
kill command will send
program1 to kill it if necessary. This has two benefits:
It can kill
program1 more quickly, since you don't have to wait for
program1 to write to the pipe and receive a
program1 is handling
SIGPIPE, it may be handling other signals as well. You can use
kill to send whatever signal is necessary (up to and including
SIGKILL, if really necessary) to terminate the process.