<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Thu, May 15, 2014 at 6:40 PM, Lennart Poettering <span dir="ltr"><<a href="mailto:lennart@poettering.net" target="_blank">lennart@poettering.net</a>></span> wrote:<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
But again, it's generally not a good idea to keep file locks for a<br>
longer period of time, much as with mutexes... You don't want to make<br>
other apps which try to get an atomic view on the file hang for long.<br></blockquote><div><br></div><div>If they don't want to hang, they don't have to. There are nonblocking calls to check for a conflicting advisory fcntl() lock. The pidfile should be private from random software anyways, other than the daemon itself and perhaps whatever tools or init system are managing start/stop.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
Actually, note that anyone who can open a file can take a lock on<br>
it. If the PID file is readable by unpriviliged users taking a lock on<br>
the PID file from the daemon is also an effective way to DoS it<br>
hence.<br></blockquote><div><br></div><div>And this can be solved with file/dir permissions (but thanks for the pointer, I hadn't considered this angle before!).</div><div><br></div><div>IMHO, the method of taking an fcntl() writelock on a private pidfile is one of the most reliable methods around for this stuff in the general case outside of systemd-land. AFAIK it's just about the only reliable way that doesn't have inherent races or accidentally kill (or be DoS'd by) unrelated processes in corner cases. You don't even have to read the contents of the pidfile (although it's polite to write them for humans to glance at), as fcntl() will give you the pid of the running daemon which currently holds the writelock. If the running daemon dies prematurely, or a system with a persistent rundir rebooted, the fcntl() lock will be gone. So there's never any confusion as to whether some other process reusing an old pid is an instance of the correct daemon or not.</div>
<div><br></div><div>As for such a portable daemon working under systemd, that's pretty trivial as well. It can continue to do the fcntl() lock on its private pidfile, not declare that pidfile to systemd, and instead use sd_notify() to send a MAINPID message after it has acquired the exclusive fcntl() lock.</div>
</div></div></div>