Is there a way that a Perl program can detect whether its STDOUT is redirected to a file?
Background of the question:

We have occasionally the problem, that on Windows a command

system(1,'perl.exe','myProg.pl','>out.txt','2>&1')
dutifully runs myProg.pl (as I can see from the files it creates), but no out.txt has been created (not even of length zero). This happens frequently enough to be annoying.

I was not able to track down the bug (there is a long story behind it - let me know if you want to hear it -, but in short, the reason is not so simple as "someone erasing out.txt before I can look at it"). My best guess is that the redirection is either not set up at all in the failure cases, or by mistake done to the bit bucket.

Of course the "right" way to solve this is to find out *why* the redirection does not work from time to time, but this looks like a difficult task, and we need at least a temporary solution. One possibility would be to test STDOUT within myProg.pl. If it is attached to a file, great (and even greater if I could find out WHICH file it is attached to, but I guess this is too much to ask). If it is attached to NUL (the Windoze equivalent to /dev/null), or if it is not redirected at all, I could close STDOUT and redirect it to a new file. This would give me the output of the file, PLUS some diagnostics of what is going on.

UPDATE:Code example corrected.
-- 
Ronald Fischer <ynnor@mm.st>

In reply to Test whether STDOUT is connected to a file by rovf

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.