Sometimes I want to killall
of a certain process, but running killall
doesn't work. So when I try to start the process again, it fails because the previous session is still running. Then I have to tediously run killall -9
on it. So to simplify my life, I created a realkill
script and it goes like this:
PIDS=$(ps aux | grep -i "$@" | awk '{ print $2 }') # Get matching pid's.
kill $PIDS 2> /dev/null # Try to kill all pid's.
sleep 3
kill -9 $PIDS 2> /dev/null # Force quit any remaining pid's.
So, Is this the best way to be doing this? In what ways can I improve this script?
It is unlikely, but it is possible that in that 3 second wait, a new process could have taken over that PID and the second kill would kill it.
Without understanding what exactly the process does, I would say it probably isn't ideal cos you may have a situation where the processes you are killing are really doing some useful shutdown/cleanup work. Forcing it down with
kill -9
may short-circuit that work and could cause corruption if your process is in fact writing data.Assuming there is no danger of data corruption and it's ok to short-circuit the shutdown, can you just
kill -9
the process the first time and be done with it. Do you have access to the developers of the process you are killing to understand what is going on that might prevent the shutdown from happening? The process might have blocked the INT and TERM for good reason.Avoid
killall
if you can since there is not a consistent implementation across all UNIX platforms. Proctools'pkill
andpgrep
are preferable:(Edit) If you have processes that are supposed to restart after being killed, you may not want to blindly kill them, so you can gather the PIDs first:
That said, you should really try to avoid using
SIGKILL
if you can. It does not give software a chance to clean up after itself. If a program won't quit shortly after receiving aSIGTERM
it is probably waiting for something. Find out what it's waiting for (hardware interrupt? open file?) and fix that, and you can let it close cleanly.