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?
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;
Edit: you should check that kpid is set, but this is more useful as it will return "not exists" for unset ${kpid}
As Anders noted, you should use
kill -0
for POSIX compliance.On Linux systems, you can also check for the existence of a file in the /proc filesystem, e.g.,
If this is in a script (which I assume is the case as you're worried about printing to stdout) then the following would be how you could do it:
The
ps -p
looks for a process with the pid specified in something.pid (the$()
syntax is a slightly newer version of the backtick. Backtick needs escaping in certain circumstances which the new form doesn't). The2>&1
redirects stderr for that command as well.If the
ps -p
command doesn't find the process with that PID it exits with a error > 0 and so theelse
gets executed. Otherwise thekill
statement. You can negate the above if you want by doing:Hope that answers your question. Obviously be careful and test a lot when using dangerous commands such as
kill
.Here are some options:
/etc/init.d/
) and if you're using Debian-based distro, you'd better usestart-stop-daemon
: You should get exit code 0 if it's running.procps
package:If you have pid file you may use pgrep to check whether process is running:
On linux you may also check for existence of
/proc/$pid
file:if you are using java on linux