Use time or until wait until PID exists

I used Bash to wait until the PID no longer exists. I tried

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

and

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

Both of these examples either do not work or continue the cycle after the completion of the process. What am I doing wrong?

+7
source share
2 answers

You should just do:

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

The loop condition checks the output status of the last command - in this case kill.

The meaning of the "last" is that you can write:

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

It also checks the status of the output kill(and killonly).

+17
source

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

while test -d /proc/$PID; do
     kill -$SIGNAL $PID
     # optionally
     sleep 0.2
done
+4
source

All Articles