You are correct, and I won't argue that semaphores have no use. But, my point was to see if my technique actually works, for use when it's the appropriate solution.

BazB wrote: Also, if you are going to just lock the file you want to modify instead of using a semaphore file, why are you opening the file, flock()ing the filehandle, closing the file (hence dropping the lock), then re-opening the file?

In the sample code I provided which I didn't specifically label as broken, I don't close the $SEM filehandle after getting a lock on it, until after I open the same file in a different filehandle, process it, and close it. That would be Wrong :)

The main use of a semaphore or second filehandle to lock a file (as opposed to the other uses you mentioned) is because you can't always open, flock, do the operations, and close the file in a straightforward way. For example, if you are doing a truncating open-for-write, you'll truncate the file before you have a lock on it. If you want to both read and write the file while it's locked, you have to either use a tricky read/write open and some seek's, or you have to open it, read it, close it, open it, then write it.

Advisory locking never "plays well with others" if one of the those "others" ignores a lock, be it on a semaphore file, or the file itself.

That's definitely true. But those aren't the cases I was talking about: I meant the cases where an existing code uses advisory locking in a known but unchangeable way, and you need to cooperate with it.

Thank you for your insight,

Alan


In reply to Re: A flock()alypse now by ferrency
in thread A flock()alypse now by ferrency

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.