LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   What does kill -0 PID do? (https://www.linuxquestions.org/questions/linux-newbie-8/what-does-kill-0-pid-do-651484/)

suicidaleggroll 11-14-2012 12:50 PM

Quote:

Originally Posted by mfirth (Post 4829395)
Sorry to resurrect this again, but another possible use for "kill -0" (or more likely the system API equivalent) is to check the existence of a process before communicating with it in another way - e.g.

If service X writes its process ID into /var/run/X.pid, then you can use 'kill -0 `cat /var/run/X.pid`' to determine if the process for X is still running.

There are obviously other ways of doing it (e.g. checking for the PID in /proc, or using grep on the output of PS), but they are probably less elegant

Hope this is useful

Michael

Or you could do the same thing by looking at the exit code of "ps -p PID".

Personally, when I'm checking if a process exists, I run "output=$(ps -p PID)", check the exit code, and if it's 0 (process is running), I go on to parse $output for the actual process name to ensure it's the right process using that PID.

Otherwise you can get a false positive when a process writes out its PID, stops running, and hours later some other process happens to be assigned the same PID. Just checking the exit code of "kill -0 PID" or "ps -p PID" in this case will tell you your process is running when it's really not, it could have exited long ago and now something else has simply been assigned that same PID.

chrism01 11-14-2012 05:18 PM

I always check the for the process name anyway, to avoid issues with erroneous pid files
Code:

ps -ef|grep procname
Gets a little more involved if you can have multiple copies running.


All times are GMT -5. The time now is 02:08 PM.