How to check whether the process ID still exists

Not well documented, but a quick and simple operation.

Try to send signal 0 to the specified process ID using kill command, then exit code will indicate whether signal may be sent.

The following example shows existing process ID.

$ pgrep firefox
4677
$ kill -0 4677
$ echo $?
0

The following example shows non-existing process ID.

$ kill -0 999999899
bash: kill: (999999899) - No such process
$ echo $?
1

The following shell script is the final example, as it will simply kill process using PID stored in the /var/run/process.pid file, if the process still exists.

#!/bin/sh
pid_file=/var/run/process.pid

kill -0 $(cat $pid_file) 2>/dev/null

if [ $? -eq 0 ]; then
  kill $(cat $pid_file)
fi

I do not understand why this is currently not mentioned in the kill manual page, but it was there [check procps-ng source code] some time ago.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu