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?