I am trying to figure out how flock interacts with read-ahead buffering on input, and I have not been able to find any documentation about it. Suppose I open and lock a file using flock for exclusive access, like this as apparently advised in the Perl Cookbook:

sysopen(FH, "numfile", O_RDWR|O_CREAT) or die "can't open numfile: $!"; flock(FH, LOCK_EX) or die "can't write-lock numfile: $!"; $num = <FH> || 0;

(I am using an exclusive lock because after reading the file, I intend to re-write it.) Between the calls of sysopen and flock, the file has been opened but has not yet been locked. Therefore, if a read-ahead buffer were filled when the file was sysopen'ed, and another process wrote to the file after that but before flock was called, then it would seem to me that the example above would be unsafe, because reading (from the read-ahead buffer) immediately after the flock could return the old file contents instead of the current contents . . . unless flock automatically invalidates the read-ahead buffer, or the read-ahead buffer is not filled until the file is actually read. But the perl documentation on sysopen, read and flock say nothing about read-ahead buffering, so I am left to guess.

Can anyone point to conclusive documentation that indicates whether the above code is actually safe (i.e., that the read operation is guaranteed to return the current file content)? Or documentation about when read-ahead buffering is done? Or how it interacts (or not) with flock? Or explain why the above code is correct, in light of this analysis?


In reply to flock and read-ahead buffering on input by dbooth

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.