10

I have been using Bash to wait until a PID no longer exists. I've tried

#!/bin/bash
while [ kill -0 PID > /dev/null 2>&1 ]; do
    //code to kill process
done
//code to execute after process is dead

as well as

#!/bin/bash
until [ ! kill -0 PID > /dev/null 2>&1 ]; do
    //code to kill process
done
//code to execute after process is dead

Both these examples either fail to work, or keep on looping after the process has ended. What am I doing incorrectly?

codeforester
  • 39,467
  • 16
  • 112
  • 140
hexacyanide
  • 88,222
  • 31
  • 159
  • 162

2 Answers2

18

You should be simply doing:

while kill -0 $PID >/dev/null 2>&1
do
    # Code to kill process
done

The loop condition tests the exit status of the last command — in this case, kill. The -0 option (used in the question) doesn't actually send any signal to the process, but it does check whether a signal could be sent — and it can't be sent if the process no longer exists. (See the POSIX specification of the kill() function and the POSIX kill utility.)

The significance of 'last' is that you could write:

while sleep 1
      echo Testing again
      kill -0 $PID >/dev/null 2>&1
do
    # Code to kill process
done

This too tests the exit status of kill (and kill alone).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
4

Also you can do in unixes with procfs (almost all except mac os)

while test -d /proc/$PID; do
     kill -$SIGNAL $PID
     # optionally
     sleep 0.2
done
Felipe Buccioni
  • 19,109
  • 2
  • 28
  • 28