close STDERR; pipe(IN,STDERR); warn "test"; close STDERR; print "X:".(<IN>);'

X:test at /tmp/ps line 3.

Make sure you close STDERR before reading from it, it hung when I did (<IN>) without first closing it. You can always re-open it before going on.

I expected that if you did something like system("find /xfkjkj") that the error message from find would also end up in IN, but it didn't. It is possible to do this, but I think you'd have to close STDIN or STDOUT first in addition to STDERR.

This has nothing to do with perl and everything to do with UNIX. When you close STDERR you are closing file descriptor 2. Then next time you open a file it will use file descriptor 2. So, when we call pipe() the input side of the pipe gets descriptor 2 and the output gets another descriptor. Now, perl writes it's warnings to STDERR, not necessarily fd 2, so everything happens as expected. But a sub-process (as created by system()) writes to fd 2 (which doesn't help us here.)

But perhaps your not on UNIX and pipe won't even work? I'll have to assume you are as I know little about other platforms.

The mini-example I posted should work and doesn't involve creating a file, but in reality you could just use a temp file and accomplish the same thing. (A temp file should work on any platform as well.)


In reply to Re: capturing STDERR within a script by SysApe9000
in thread capturing STDERR within a script by kiz

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.