1

我有两个后台进程 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 将给出该 pid 的行数,因为 grep 将在 ps -ef 中至少有一个输出,因为它也作为 PID 运行,它至少有 1 个结果

即使你 ps -ef | grep someID 将有一个 pid 用于 grep

于 2013-10-28T10:53:48.687 回答