Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

redirecting default STDOUT for system() calls

Status
Not open for further replies.

gkmccone

Technical User
Oct 24, 2001
17
US
OK, I want to redirect all the STDOUT of a system( cmd ) to
a log file.

Now I know you are saying, "Hey thats simple, just use a
redirection metacaracter in the system() call, like
system( cmd > /dir/logFile).", but what if your system
doesn't support those shell metacaracter???????

It seems that you should be able to redefine the default
STDOUT, STDIN, STDERR definitions that are inherited by the
system() call, but

open( LOG, /dir/logFile);
*STDOUT = *LOG;
*STDERR = *LOG;
print "This is STDOUT";
print STDERR "This is STDERR";
system( "dir" );

still allows the dir's OUT and ERR to go to the terminal
while the print "This is STDOUT"; and
print STDERR "This is STDERR";
go to the LOG file.

Any Perl Gurus out there????
 
I did 'perldoc -q STDERR' and found this:

Found in /usr/lib/perl5/5.6.1/pod/perlfaq8.pod
How can I capture STDERR from an external command?

There are three basic ways of running external commands:

system $cmd; # using system()
$output = `$cmd`; # using backticks (``)
open (PIPE, "cmd |"); # using open()

With system(), both STDOUT and STDERR will go the same
place as the script's STDOUT and STDERR, unless the sys­
tem() command redirects them. Backticks and open() read
only the STDOUT of your command.

With any of these, you can change file descriptors before
the call:

open(STDOUT, ">logfile");
system("ls");

or you can use Bourne shell file-descriptor redirection:

$output = `$cmd 2>some_file`;
open (PIPE, "cmd 2>some_file |");

You can also use file-descriptor redirection to make
STDERR a duplicate of STDOUT:

$output = `$cmd 2>&1`;
open (PIPE, "cmd 2>&1 |");
----------------------------------------
That's just a start - there's more info in that perldoc.

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
Hey, thanks for the reply.

It works when you directly open STDERR or STDOUT using:

open(STDOUT, "> logfile");

but doing a

open(LOG, "> logfile");
*STDOUT = *LOG;


doesn't, and I don't upderstand how they differ.

Maybe the key lies in the depths of perldoc. I'll give it
a look.
 
Check out the perlfunc documentation for the open command. It shows you how to save, redirect and restore STDOUT and STDERR. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top