marc
marc

Reputation: 971

Dealing with background processes in bash

I have two background processes 1 and 2

./1.sh &
 PID_1 = $!

./2.sh &
 PID_2 = $!

I'm trying to identify the process that finishes first and then kill that process which is still continuing. This is the script I'm working on.

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

While this script works, I'm looking if there is any other better way of doing this.

Upvotes: 1

Views: 254

Answers (3)

Ashish
Ashish

Reputation: 1952

Try it this way

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 will give number of lines with that pid since grep will have atlest one output in ps -ef as it also runs as a PID it have atleast 1 result

even if you ps -ef | grep someID will have one pid for grep

Upvotes: 0

pinoyyid
pinoyyid

Reputation: 22296

You can use wait. Something like ...

 (1.sh& wait $!; killall 2.sh)&
 (2.sh& wait $!; killall 1.sh)&

Upvotes: 0

anubhava
anubhava

Reputation: 785126

You can use use this simple approach for this task:

  1. Use trap SIGCHLD to register a custom handler at the start of your script.
  2. Every time a background (child) process exits, this custom handler will be invoked.
  3. Inside the custom handler use jobs -l to see which child process is still running and kill it.

Upvotes: 1

Related Questions