One of the common problems people have with file locking is failing to append correctly. Your verbatim example didn't suggest that you were appending, but if other snippets of your code read
open(FILE, ">>$path") or die "$! writing $path"; &lock; # calls flock(FLOCK_EX) and logs print FILE $string; &unlock; # calls flock(FLOCK_UN) and logs close FILE;
then you have a race condition that can cause file corruption.

Consider what happens if the open succeeds and the flock blocks to obtain the lock. The open has positioned you for writing to the end of the file. But if the process that holds the lock writes after you've opened the file, the end-of-file mark moves. You're now positioned to overwrite whatever the other process wrote. If your string is longer, their string gets lost. If your string is shorter, you probably corrupt the file.

The way around this is to seek to end-of-file after you've obtained the lock.

open(FILE, ">>$path") or die "$! writing $path"; &lock; seek(FILE, 0, 2); # ensure positioned at EOF print FILE $string; ...

Update: This also applies when truncating a file. Only truncate after you've obtained an exclusive lock. If you truncate before locking, you risk pulling the rug out from under whatever process does have the lock.


In reply to Re: Re: Re: File locking, lock files, and how it all sucks by dws
in thread File locking, lock files, and how it all sucks by tocie

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.