I'm writing a Perl script that parses logfiles to collect PIDs and then checks whether that PID is running. I am trying to think of the best way to make that check. Obviously, I could do something like:
system("ps $pid > /dev/null") && print "Not running\n";
However, I'd prefer to avoid the system call if possible. I therefore thought I could use the /proc
filesystem (portability isn't a concern, this will always be running on a Linux system). For example:
if(! -d "/proc/$pid"){
print "Not running\n";
}
Is that safe? Can I always asume that if there's no /proc/$pid/
directory the associated PID is not running? I expect so since AFAIK ps
itself gets its information from /proc
anyway but since this is for production code, I want to be sure.
So, can there be cases where a running process has no /proc/PID
directory or where a /proc/PID
directory exists and the process is not running? Is there any reason to prefer parsing ps
over checking for the existence of the directory?
kill
function using signal 0 which does no killing but says if you could do so (ie you need permission to signal that process). – meuh Jul 10 '16 at 17:48/proc
(see/proc/2
for example), i'm confident (80% sure) that/proc
reflects the process table inside the kernel. And, if a process is not on the process table it will not be caught by the scheduler, and therefore will never run (so it cannot be a running process). – grochmal Jul 10 '16 at 17:58kill -0
is the best one), this only tells you whether there is a running process with the given PID. It doesn't tell you whether the process will still be running one millisecond later, and it doesn't tell you whether the process is the one you're interested in or an unrelated process that got assigned the same PID after the interesting process died. It is almost always a mistake to test whether a given PID is running: there are very few circumstances where this isn't prone to race conditions. – Gilles 'SO- stop being evil' Jul 10 '16 at 19:50