develooper Front page | perl.perl5.porters | Postings from November 2005

Capturing STDOUT

Brett Wooldridge
November 22, 2005 18:39
Capturing STDOUT
Message ID:
I have a question that I'm hoping one of you can answer.  I am running Perl
embedded in another application, and need to be able to capture STDOUT
output from the Perl script.  Looking at how mod_perl accomplishes this was
useful but not usable for my use case.

The way mod_perl appears to do it is:

  1.  dup the STDOUT handle
  2.  close it
  3.  reopen it using the mod_perl custom IO layer
  4.  capture the output
  5.  restore the STDOUT handle

This doesn't work for me because in step 2) above, when I close it, it is
closing the actual STDOUT handle of the containing application (in which
perl is embedded).  This means that STDOUT output from other (non-perl)
threads in the containing application is effectively shutoff, as well.

It was my impression that with PerlIO layers I would be able to "intercept"
reads/writes from STDOUT, but I don't know how to accomplish this -- even
after reading the perlio, perlguts, perlrun, perlembed pods.  I've read the
'scalar' and 'encoding' PerIO implementations but still don't have an idea
how to intercept STDOUT.  I can insert my own PerlIO layer, like mod_perl
does, and I can capture STDOUT, but only by first closing the original
STDOUT handle.

I think what I need is for my PerlIO layer to be inserted *before* the stdio
layer (possibly), and then theoretically I would get called for the open()
of STDOUT before the stdio layer, and would be able to intercept it.  Or
possibly when I create my embedded interpreter, I need to "pop" off the
stdio layer, and then insert mine -- but I don't know what happens if the
STDOUT handle has already been opened.

Can anybody here give me some guidance?  I've been going in circles on this

Brett Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About