I持つバックグラウンドプロセスとして無限のコマンドを実行しますbashの:bashシャットダウンフック;メインプロセスが殺されたときや、すべてのバックグラウンド・プロセスを殺す
#!/bin/bash
function xyz() {
# some awk command
}
endlesscommand "param 1" | xyz & # async
pids=$!
endlesscommand "param 2" | xyz & # async
pids="$pids "$!
endlesscommand "param 3" | xyz # sync so the script doesn't leave
このスクリプトを停止する唯一の方法はある(なければなりません)はCtrl-Cまたは殺すとその場合、$ pids変数にリストされているすべてのバックグラウンドプロセスを強制終了する必要があります。 どうすればいいですか?
私のようなものだろうメインプロセスにkillシグナルをキャッチし、それが起こるとき(シャットダウンフック)関数を実行することが可能であった場合は、次の
for $pid in $pids; do kill $pid; done;
をしかし、私は見つけることができませんどのように次の記事からこれを行う...
SOLUTION:
#!/bin/bash
function xyz() {
# some awk command
}
trap 'jobs -p | xargs kill' EXIT # part of the solution
endlesscommand "param 1" | xyz & # async
endlesscommand "param 2" | xyz & # async
endlesscommand "param 3" | xyz & # don't sync, but wait:
# other part of the solution:
while pgrep -P "$BASHPID" > /dev/null; do
wait
done
トラップを使用する必要があります... – devnull
子プロセスの明示的なリストを維持する必要はありません。 'jobs -p'を呼び出して、まだ実行中の子プロセスIDを取得することができます。 – chepner