check process id exists

kill -0 pid

sending the signal 0 to a given PID just checks if any process with the given PID is running and you have the permission to send a signal to it.

$ 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.

check exists, return 0

$ pgrep httpd
46775
$ kill -0 46775
$ echo $?
0

check non-exists, return 1

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

kill process id stored in .pid file

#!/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

你可能感兴趣的:(check process id exists)