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?
killfunction using signal 0 which does no killing but says if you could do so (ie you need permission to signal that process).kill -0is 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.