One of the idioms often used to check if process is running is to use
kill -s 0 $pid.
My question is, does it have any upsides over using
[[ -e /proc/$pid ]] construct?
The script I'm writing is both Linux and bash specific.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
I would generally use a command such as
kill over reading content directly from
/proc. The upside is that a tool such as
kill will return status codes (think
$?) if it was successful, or not, and should in theory already have any API related things included, when it's dealing with
/proc content vs. rolling it yourself.
Additionally using dedicated commands makes for better portability of your code across the various Unixes.
/proc is not ubiquitous on other Unixes such as Solaris and AIX.
Test process to kill.
$ sleep 10 &  11639
Now we kill it.
$ kill 11639 + Terminated sleep 10
Were we successful?
$ echo $? 0
A zero means we were successful. Anything else, we could handle it in different ways. With reading the
/proc directly, we're left in a bit of a quandary.
Same situation, we're attempting to kill a non-existent process.
$ kill 61234 bash: kill: (61234) - No such process
We get feedback about it.
$ echo $? 1
You may also want to investigate using
pgrep too if you'd rather kill or look for a process by name, rather than
$pid. But it depends ultimately on what you're trying to do.
There is a major difference between
kill -s 0 $pid and
[ -e /proc/$pid ]. The latter tests whether there is a process (or zombie) with this PID. The former only matches processes (or zombies) to which you can send a signal, i.e. the process's real or saved UID must be the same as the UID of the shell you're running this from (unless the shell is running as root, in which case there is no difference).
Which one to use depends on whether you want to match other users' processes.
kill -s 0 $pid is very portable (it's POSIX-compliant). Testing for
/proc/$pid doesn't work on BSD unices as they don't have
/proc; a portable way of achieving the same effect is
ps -p $pid >/dev/null 2>/dev/null.