I've written a function that writes some data to an output filehandle that is passed to it.

At the moment, the function does a flock $fh, LOCK_EX | LOCK_NB call before writing the data, but this fails if the caller passes in the STDOUT filehandle.

Apparently you cannot flock() STDOUT, at least not on my system - Win32. Is this generally the case on other platforms?

If so, then what is the best plan to avoid this situation?

I could either remove the flock() call from my function and add some documentation that the caller may want to flock() the filehandle itself before passing it in to my function, or I could have my function try to identify STDOUT (and likewise STDERR) and only do the flock() if the filehandle is not STDOUT.

If I chose the latter strategy then how would I identify STDOUT? Just testing if (fileno $fh == 1) is no good because if STDOUT has been dup'ed and redirected, e.g.

open SAVOUT, '>&STDOUT'; close STDOUT; open STDOUT, '>stdout.txt';

then we now find that fileno(SAVOUT) != 1 but can't be flock()'ed, while fileno(STDOUT) == 1 and can now be flock()'ed.

Thanks,
- Steve


In reply to Avoiding accidentally flock()'ing STDOUT by shay

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.