The polite approach has you request a shared lock for reading and an exclusive lock for writing. (That's LOCK_SH and LOCK_EX, respectively.)

On a non-braindead operating system, many processes can simultaneously acquire a shared lock on a file, but an exclusive lock can only be held by one, and it usually blocks until all other locks (including shared locks) are released.

You have a couple of options. You could open the file for read/write access with an exclusive lock, at the beginning of your program. That's conceptually simple, but you'll have to "rewind" it after reading, if you want to overwrite it. (See seek.) It also has the drawback that if another process has any lock on the file, your program will block (unless you work around it). This is the technique I'd choose.

You could also continue with the code above. If you don't close the filehandle explicitly, Perl will do that for you implicitly. Closing a filehandle has the side effects of flushing buffers and unlocking any locks on it.

I doubt your code to open the filehandle to a different file and acquire an exclusive lock is an atomic operation. (It probably takes more than one processor cycle to accomplish, so there is a possibility another process could jump in there and grab a lock. Of course, any process that doesn't check for locks could do that anyway.)

The best advice I can think of is to make sure that any other process that might access the file also use the same flock technique you decide on.

Disclaimer: I'm not as smart as I seem, sometimes.


In reply to Re: Flocking by chromatic
in thread Flocking by mt2k

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.