5
votes

I want to create a bash script that will launch two processes and kill the second process when the first is done. Here's an example:

#fork first process
producer&

#fork second process
consumer&

#wait for producer to finish
...

#kill the consumer
...

I have a feeling this can get ugly but has a very simple solution. Please help me fill in the blanks.

2

2 Answers

12
votes
foo & pid_foo=$!
bar & pid_bar=$!

wait $pid_foo
kill $pid_bar

But perhaps you could just run foo | bar (if that happens to work with stdin/stdout handling).

3
votes
#!/bin/bash 

#enable job control in script
set -m

producer &

consumer &

fg %1

kill %2