Checking Whether a Process Exists

On Linux/Unix systems, there's occasionally the need to check whether a process is running. Some people use it for simple status checks or when building their own lifecycle scripts for startup and shutdown. I don't think it's a particularly good practice these days because all of this can be achieved with tools like systemd, supervisord, JavaServiceWrapper, or even Docker. But if you can't use these for some reason, read on.

A lot of badly written scripts I've seen resort to things like pgrep(1), pidof(1), or some variation of these. In the case of shutdown scripts they sometimes ended up killing way more than they intended, or nothing at all. Traditionally, there's a much better and completely platform-independent way.

When starting a service in the background, save the service's process ID (PID) in a file. If the service doesn't do that already (look for files in /var/run/, ending with ".pid") then the $! shell variable will give you the PID of the last background process you started. Save it to a file:

echo $! > /var/run/

If the process dies at some point, you will have stale PID file referencing an process that no longer exists. Note that PIDs get reclaimed after a while, but if your service runs under its own user account, the chance of killing an unrelated process is minimal.

To check whether the process is still running, use the kill(1) command which works if you own the process or if you're root:

kill -0 $(cat /var/run/ 2> /dev/null

This won't kill the process but rather give you a 0 return code if the process is running or a return code of 1 if the process isn't running or you don't own it. If you do need to kill the process, modify the command line to send a different signal:

kill $(cat /var/run/

Like I said - very simple, but don't use it unless you have to.