The O_EXCL (Fail if the file already exists) option causes sysopen to fail if the file already exists (surprise). This lets you attempt to create the file (O_RDWR|O_CREAT), but prevents you from taking over the file if it already exists (someone else has already created it), making it an effective lock for situations where you just can't use (or trust) flock.

Without it, one process would create the file, and the next process would simply open it again without waiting for it to be removed. In your example, the initial lock file still maintains counts of clients but since it's now being locked by the .lock file, there's no need to flock it anymore. The new .lock file restricts access to your initial lock file so clients can be sure that files don't change out from under them.

In the "timeout checking code" bit (which I didn't include) you should probably check for things like dead lock files. If your system crashes after the .lock file has been created and before it's removed, then the file will sit around for ever locking out your application. Usually you want to check the mod time of the .lock file and remove it if it's older than some arbitrary time limit (which will depend on your application needs). You probably also want to exit the loop (or die) if you've waited too long to open the .lock file.


In reply to Re^3: File Locking plus delete Lockfile question by ruzam
in thread File Locking plus delete Lockfile question by rovf

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.