How to check if a process id (PID) exists

The best way is:

if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with kill -0 $PID is that the exit code will be non-zero even if the process is running and you don’t have permission to kill it. For example:

kill -0 $known_running_pid

and

kill -0 $non_running_pid

have a non-zero exit codes that are indistinguishable for a normal user, but one of them is by assumption running, while the other is not.


Partly related, additional info provided by AnrDaemon: The init process (PID 1) is certainly running on all Linux machines, but not all POSIX systems are Linux. PID 1 is not guaranteed to exist there:

kill -0 1 
-bash: kill: (1) - No such process … 

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a “kill”. I came looking for the general “how do you test for a PID existence in bash“.

The /proc method is interesting, but in some sense breaks the spirit of the ps command abstraction, i.e. you don’t need to go looking in /proc because what if Linus decides to call the exe file something else?

Leave a Comment