代码之家  ›  专栏  ›  技术社区  ›  marc

处理bash中的后台进程

  •  1
  • marc  · 技术社区  · 11 年前

    我有两个后台进程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
    

    虽然这个脚本有效,但我正在寻找其他更好的方法。

    3 回复  |  直到 11 年前
        1
  •  1
  •   anubhava    11 年前

    您可以使用以下简单方法执行此任务:

    1. 使用 trap SIGCHLD 在脚本开始时注册一个自定义处理程序。
    2. 每次后台(子)进程退出时,都会调用此自定义处理程序。
    3. 在自定义处理程序内部使用 jobs -l 查看哪个子进程仍在运行,以及 kill
        2
  •  0
  •   pinoyyid    11 年前

    你可以使用等待。有点像。。。

     (1.sh& wait $!; killall 2.sh)&
     (2.sh& wait $!; killall 1.sh)&
    
        3
  •  0
  •   Ashish    11 年前

    这样试试

    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 将有一个用于grep的pid