Bash snippet for killing a process until it’s dead

bashkillprocessscriptingsnippet

I'm trying to write a robust bash script, and in it I create a background process. At the end of the script, I want to kill it. I have it's PID.

I was thinking of somthing like this

while [[ ps ef $PID ]] ; do
  kill $PID
  sleep 0.5
done

Any suggests for anything better? Any possible problems with this approach?

Best Answer

The problem with repeatedly killing a process is that you've got a race condition with new process creation. It's not particularly likely, but it's possible that the process will exit and a new process start up with the same PID while you're sleeping.

Why are you having to repeatedly kill the process? If it's because the process will exit, but it may take some time to quit after receiving the signal, you could use wait:

 kill $PID
 wait $PID

In an ideal system, you'd never have to repeat a kill or issue kill -9 $PID. If you do have to, you might want to consider fixing whatever it is that you're running so you don't have to. In the meantime, you will probably not hit the race condition, and you can guard against it by (say) checking the timestamp of /proc/$PID/ just before killing the process. That's bad hackiness, though.