I recently came across this in a shell script.
if ! kill -0 $(cat /path/to/file.pid); then
... do something ...
fi
What does kill -0 ...
do?
killprocessshell
I recently came across this in a shell script.
if ! kill -0 $(cat /path/to/file.pid); then
... do something ...
fi
What does kill -0 ...
do?
Best Answer
This one is a little hard to glean but if you look in the following 2 man pages you'll see the following notes:
kill(1) kill(2)So signal 0 will not actually in fact send anything to your process's PID, but will check whether you have permissions to do so.
Where might this be useful?
One obvious place would be if you were trying to determine if you had permissions to send signals to a running process via
kill
. You could check prior to sending the actualkill
signal that you want, by wrapping a check to make sure thatkill -0 <PID>
was first allowed.Example
Say a process was being run by root as follows:
Now in another window if we run this command we can confirm that that PID is running.
Now let's try this command to see if we have access to send that PID signals via
kill
.So it works, but the output is leaking a message from the
kill
command that we don't have permissions. Not a big deal, simply catch STDERR and send it to/dev/null
.Complete example
So then we could do something like this,
killer.bash
:Now when I run the above as a non-root user:
However when it's run as root: