
理論上,使用此區塊,您應該只看到“正在運行...”一次(或更少),但實際上,它會重複,直到手動終止。呼叫函數“start”後,如何從分叉進程外部將分叉進程內部的 x 值更改為 false?
export x=true
start() {
while [ $x == true ]; do
echo running...
sleep 1
done
}
start &
x=false
答案1
這裡的簡單解決方案是使用某種進程間通訊來告訴目標進程進行更改。例如,您可以使用訊號:
#!/bin/sh
export x=true
start() {
trap x=false USR1
while [ $x = "true" ]; do
echo running...
sleep 1
done
}
start &
sleep 5
kill -USR1 $!
wait
產生這個輸出:
$ ./testit.sh
running...
running...
running...
running...
running...
$
答案2
如果您使用的是ksh93
,則可以使用紀律函數來實現共享變數(請參閱https://stackoverflow.com/questions/13726293/environment-variables-to-be-used-across-multiple-korn-ksh93-shell-scripts-get)
或者,您可以使用fish
它透過守護程序實現此功能:魚d。