shay has asked for the wisdom of the Perl Monks concerning the following question:

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

Replies are listed 'Best First'.
Re: Avoiding accidentally flock()'ing STDOUT
by gellyfish (Monsignor) on Aug 13, 2004 at 09:02 UTC

    You might try using the -t file test operator, this should be able to tell you whether a handle is opened to TTY (and hence not flock()able) and not to a file:

    print "Yow!" if -t STDOUT; open SAVOUT, '>&STDOUT'; close STDOUT; open STDOUT, '>stdout.txt'; print "Yow!" if -t STDOUT;

    /J\

      Brilliant! The simple solutions are always the best.

      Thanks very much -- that works a treat.

      - Steve