Linux – What’s a proper way of checking if a PID is running

bashlinuxpidprocessunix

I have a .pid file, and I need to check if the process is running. So far I found two options

kill -0 `cat something.pid`

which prints out an error if the pid isn't running. I know this can be redirected to /dev/null, but it makes me think that this isn't the best solution.

The second solution would be to use ps, which however also prints on the STDOUT

ps -ef `cat something.pid`

Is it normal to redirect the output to /dev/null and just use the status code returned, or is it a sign that I'm doing something wrong and I need a different command?

Best Answer

for most linux distros enumerating the /proc/{pid} is a good way to obtain information about the running processes, and usually how the userspace commands like "ps" are communicating with the kernel. So for example you can do;

[ -d "/proc/${kpid}" ] && echo "process exists" || echo "process not exists"

Edit: you should check that kpid is set, but this is more useful as it will return "not exists" for unset ${kpid}

[ -n "${kpid}" -a -d "/proc/${kpid}" ] && echo "process exists" || echo "process not exists"