You've already received very good advice. But since you mentioned you're paranoid, you should also be aware that lock-based solutions do not work reliably under (most) NFS mounts.

This happens because the locking protocol must be properly supported in the client _and_ in the server. Since so many people just asume this is broken, many vendors don't pay much attention to fixing it.

One nice way to reasonably insure that your process is the only instance in a machine, is to use a socket. Just grab yourself an unused port number (under < 1024 if you can, as this woule be better) and bind() it to your localhost address.

The first instance won't have problems. Any subsequent instance will fail at the bind() with an Address already in use error. If you init the pid file after a succesful bind(), you won't wipe the pid file incorrectly. When the first instance dies for whatever reason, the OS will take care of removing the socket for you.

Binding the socket to the localhost address, prevents it from being reached from another host via the network, so only local processes could connect to it. By choosing a port number < 1024, you insure that only a process with root priviledges could do the same and spoil this scheme.

I don't know what else do you do in your scenario, but perhaps this socket could also have practical uses, such as pulling or feeding data to the daemon.

Regards.


In reply to Re: Writing to flock files in a daemon by fokat
in thread Writing to flock files in a daemon by graq

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.