To expand a little on what has already been said: flock will wait, until it gets a lock. If it does not get one, it is not likely to the next time you try either. Your code might be useful if it was used for open instead of flock, then, once the open was successful, do the flock. Once. If it's going to fail, it's going to fail here. Also, you should only use LOCK_EX when you want to write to the file, and then do your writing as fast as possible, and unlock it as soon as possible. The problem with LOCK_EX is that it not only locks your file, but creates a bottleneck, as only one process can access the file at a time. With LOCK_SH, many processes can read the file simultaneously, although they cannot write to it.

Also, you might want to write

my $file = shift; ## instead of my $file = pop();
That way, if you ever add more parameters, (the kind of lock perhaps?) the filename can remain the first parameter, which reads better and fits in with general layout of most significant to least significant in an argument list (i.e. perl functions always have their optional arguments at the end)


In reply to RE: Flock Subroutine by turnstep
in thread Flock Subroutine 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.