2010-04-22 32 views
5

我想創建一個bash腳本,它將啓動兩個進程並在第一個進程結束時終止第二個進程。這裏有一個例子:分叉兩個進程並在完成第一個時殺死第二個進程

 
#fork first process 
producer& 

#fork second process 
consumer& 

#wait for producer to finish 
... 

#kill the consumer 
... 

我有一種感覺,這可以變醜,但有一個非常簡單的解決方案。請幫我填空。

回答

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

wait $pid_foo 
kill $pid_bar 

但也許你可以只運行foo | bar(如果出現這種情況與標準輸入/輸出處理工作)。

+0

管道是聰明的,但也許你不想 – frankc 2010-04-22 21:32:02

+1

你不需要的PID的標準輸入/輸出的後果,你可以使用%1%2 – topskip 2010-04-22 21:32:54

+1

@Patrick:如果這兩個進程實際上只是編號這可能是有道理的。但是,在一般情況下,將變量'pid_foo'和'pid_bar'命名是更有意義的,讀取代碼比'%1'和'%2'更清晰。不過,多謝提及這種可能性(至少在bash中)。 – ndim 2010-04-22 21:55:11

3
#!/bin/bash 

#enable job control in script 
set -m 

producer & 

consumer & 

fg %1 

kill %2