Home  |  Linux  | Mysql  | PHP  | XML
From:Eric Veith Date:Thu Jul  2 08:36:17 2009
Subject:Redirecting STDOUT and STDERR for system()

Hello List,

as part of a Perl script of mine, I want to execute a program, get its
return code AND capture its output on both STDERR and STDOUT. I tried
IO::Handle, but that only gives me STDOUT and not the return code. Using
qr//, I cannot read linewise and have to load the complete program's output
into memory first, which I want to avoid. (Please feel free to correct me
on anything of the above.)

What I tried to archive now can be summarized in this little script:

my $stdout = IO::File->new('stdout', 'w');
my $stderr = IO::File->new('stderr', 'w');

my $pid = fork();
die("Could not fork, stopping") if(not defined $pid);

if(0 == $pid) {
*STDOUT = $stdout;
*STDERR = $stderr;
system("df", "-h");
my $rc = $?;
$stdout->flush(););
exit($rc << 127););
} else {
print "Parent.\n";;
wait();
print "RC=$?\n";
}

$stdout->close();
$stderr->close();


That does not, however, work as expected. I do get STDERR's output (if I,
for example, change the command in system() to something that does not
work, e. g. system("df", "garbage", "-FOO"); the error is to be found in
the stderr file), but not the output on STDOUT -- that is printed out on
screen just as usual.

What am I missing here? How can I do a fork, re-open STDOUT/STDERR to write
to an instance of IO::Handle, and get the return code?

Thanks for any hints.

-- Eric

Navigate in group perl.beginners at sever nntp.perl.org
Previous Next


Your recent visits
Re: Need help with Mail::Sender
variable scope
Re: Rendering data structures using CGI::Application
Re: Using Heap::Elem
AW: exit status



  
© No Copyright
You are free to use Anything, but please consult your advocate before doing so as this website
also list content from other sources which may be copyrighted.
Site Maintained by Zareef Ahmed
Powered By PHP Consultants