linux What does kill 0 do
What does kill -0 ...
do?
if ! kill -0 $(cat /path/to/file.pid); then
... do something ...
fi
kill(1)
$ man 1 kill
...
If sig is 0, then no signal is sent, but error checking is still performed.
...
kill(2)
$ man 2 kill
...
If sig is 0, then no signal is sent, but error checking is still performed;
this can be used to check for the existence of a process ID or process
group ID.
...
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 actual kill
signal that you want, by wrapping a check to make sure that kill -0 <PID>
was first allowed.
Example
Say a process was being run by root as follows:
$ sudo sleep 2500 &
[1] 15693
Now in another window if we run this command we can confirm that that PID is running.
$ pgrep sleep
15693
Now let’s try this command to see if we have access to send that PID signals via kill
.
$ if ! kill -0 $(pgrep sleep); then echo "You're weak!"; fi
bash: kill: (15693) - Operation not permitted
You're weak!
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
.
$ if ! kill -0 $(pgrep sleep) 2>/dev/null; then echo "You're weak!"; fi
You're weak!
Complete example
So then we could do something like this, killer.bash
:
#!/bin/bash
PID=$(pgrep sleep)
if ! kill -0 $PID 2>/dev/null; then
echo "you don't have permissions to kill PID:$PID"
exit 1
fi
kill -9 $PID
Now when I run the above as a non-root user:
$ ~/killer.bash
you don't have permissions to kill PID:15693
$ echo $?
1
However when it’s run as root:
$ sudo ~/killer.bash
$ echo $?
0
$ pgrep sleep
$