Detecting a stale pid file in a Unix environment
Asked Answered
N

2

2

What is the standard, cross-platform way to detect stale pid file in a Unix environment? Say I would like to kill an old instance of my application, but I certainly don't want to disrupt an unrelated process with the same PID if that application has already exited.

Now I found a way to do it on my Ubuntu (and thus probably other GNU/Linux based systems) - pseudocode below:

if ( mtime(pid_file) < mtime( "/proc/"+pid ) ) {
     /* process started AFTER the file creation */
     /* so it's not what we're looking for */
     unlink(pid_file);
     return 0;
};
/* proceed to kill & do all stuff */

But would such hack work on other systems? Anyway it should be a standard task with a solution known for 30+ years.

Found a similar question here, but failed to find a definite answer to my question.

Thank you.

Nelsen answered 23/10, 2016 at 17:16 Comment(1)
Does not work on MacOS. I'm trying to find a fully POSIX approach and it's difficult.Waiver
F
3

File times at /proc/ date back to at least 1991; see p. 243. And, although mtime can be faked (e.g. via touch -m --date=<needed_date> <target_file>), for a userland app there is no way to do so on its own /proc/ entry.

Fortuna answered 26/10, 2016 at 16:2 Comment(0)
W
0

Even on Linux this approach is not 100% reliable as there is evidently a race condition on /proc entry creation.

Example output from an Ubuntu 20 system:

# bash -c 'echo $$ > pidfile; ls -ld --full-time pidfile /proc/$$'
-rw-r--r-- 1 root root 7 2024-03-07 03:15:28.888043061 +0000 pidfile
dr-xr-xr-x 9 root root 0 2024-03-07 03:15:28.892043050 +0000 /proc/719367

As you can see here, the /proc entry is shown as newer than the pidfile. So the process "started after" the file creation, but it is definitely the one you're looking for.

You could probably add some fudge figure to get around this but you'd better decide in which direction you want to err: have some false positives, or some false negatives.

Most likely, this race condition won't come up in practice, as few applications would immediately write to the pidfile as their very first action on starting.

I ran into this during testing of pidfile handling, as I was trying to simulate different scenarios such as: pidfile older than running process, pidfile newer than running process. I didn't account for the possibility that pidfile would be a fraction of a second older than running process even though it was created by that process, so my tests weren't working.

Waiver answered 7/3 at 3:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.