はい、trap
コマンドで信号を傍受できます。以下の例を参照してください。
#!/bin/bash
function wrap {
local flag=0
trap "flag=1" SIGINT SIGTERM
xeyes &
subppid=$!
while :
do
if [ $flag -ne 0 ] ; then
kill $subppid
break
fi
sleep 1
done
}
flag=0
trap "flag=1" SIGINT SIGTERM
wrap &
wrappid=$!
while : # This is the same as "while true".
do
if [ $flag -ne 0 ] ; then
kill $wrappid
break
fi
sleep 1 # This script is not really doing anything.
done
echo 'end'
trap
基本的には、"" の間のコマンドを実行することです。したがって、ここでは main 関数が以下の while ループにあります。反復ごとに、スクリプトはフラグが設定されているかどうかをチェックし、設定されていない場合は 1 秒間スリープします。その前に、子プロセスの pid を$!
. SIGINT
orがキャッチされると、トラップはコマンドを発行しますSIGTERM
(他のシグナルについては、kill
マニュアルを参照してください)。
ラッパー関数は、メイン関数と同じことを行います。さらに、実際のsubprocess
関数を呼び出します (この場合、サブプロセスは ですxeyes
)。ラッパー関数SIGTERM
がメイン関数からシグナルを受信すると (メイン関数もシグナルの 1 つをキャッチした場合)、ラッパー関数は実際にサブプロセスを強制終了する前にクリーンアップできます。その後、while ループから抜け出し、ラッパー関数を終了します。次に、メイン関数も中断して出力し'end'
ます。
編集:これを正しく理解していることを願っています。実行を余儀なくされていますxeyes &
。次に、手順は次のようになります(ターミナルで):
xeyes &
subpid=$!
trap "kill $subpid && exit " SIGINT SIGTERM
.... other stuff
.... more stuff
^C #TERMINATE - this firstly kills xeyes and then exits the terminal