1

私は2つのバックグラウンドプロセス1と2を持っています

./1.sh &
 PID_1 = $!

./2.sh &
 PID_2 = $!

最初に終了するプロセスを特定してから、まだ継続しているそのプロセスを強制終了しようとしています。これは私が取り組んでいるスクリプトです。

while ps -p | grep " $PID_1"
do
     ## process 1 is still running
     ### check for process 2

     if ! ps -p | grep "$PID_2" 
     then
          ### process 2 is complete, so kill process 1
          kill $PID_1
     fi
done

kill $PID_2 ## process 2 is still running, so kill it

このスクリプトは機能しますが、他にもっと良い方法がないか探しています。

4

3 に答える 3

1

このタスクには、次の単純なアプローチを使用できます。

  1. trap SIGCHLDスクリプトの開始時にカスタム ハンドラーを登録するために使用します。
  2. バックグラウンド (子) プロセスが終了するたびに、このカスタム ハンドラーが呼び出されます。
  3. カスタム ハンドラー内で、jobs -lどの子プロセスがまだ実行されているかを確認するために使用しますkill
于 2013-10-28T10:47:28.050 に答える
0

待機を使用できます。何かのようなもの ...

 (1.sh& wait $!; killall 2.sh)&
 (2.sh& wait $!; killall 1.sh)&
于 2013-10-28T10:50:44.807 に答える
0

こうやってみる

while true
   do

     res1=`ps -p | grep -c "$PID_1"`
     res2=`ps -p | grep -c "$PID_2"`
#grep command itslef will consume one pid hence if grep -c = 1 then no process else if greator than process is running 
    if [ $res1 -eq 1 ]
     then
      kill -9 $PID_2;
      exit 
     #exit while loop and script
   elif [ $res2 -eq 1 ]
      kill -9 $PID_1;
      exit
     #exit while loop and script
   fi
done

grep -c は、grep が ps -ef で少なくとも 1 つの出力を持つため、その pid の行数を示します。PID としても実行されるため、少なくとも 1 つの結果があります。

ps -ef | grep someID には、grep 用の pid が 1 つあります。

于 2013-10-28T10:53:48.687 に答える