Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Execute command, show realtime output and get exit code

by afunix (Initiate)
on Nov 01, 2011 at 12:24 UTC ( #935100=perlquestion: print w/ replies, xml ) Need Help??
afunix has asked for the wisdom of the Perl Monks concerning the following question:

Hello!

I need to execute command, display it's output and get exit code.
open(X, '-|', 'cmd') is a good one, but it returns pid in this form and $? is zero, so I can't get a return code.
`cmd` can do everything, but it returns output after command was executed, and I need to display output and put it into log file, just like tee.
There is one more way, the most complicated:
my $pid = open(PIPE, '-|'); die "open(): $?" unless (defined $pid); if ($pid) { while (<PIPE>) { print $_; } close(PIPE); } else { die "system(): $!" unless (system($cmd)); die "failed to execute: $!" if ($? == -1); die "signal: ". ($? & 127) if ($? & 127); die "exit code: ". ($? >> 8) if ($? >> 8); }
There is just one problem. I need to deliver $? into parent process...

So, dear monks, is there any way to receive command output in a realtime and get it's exit code in some easy way?

Comment on Execute command, show realtime output and get exit code
Download Code
Re: Execute command, show realtime output and get exit code
by Eliya (Vicar) on Nov 01, 2011 at 19:31 UTC
    ...and $? is zero, so I can't get a return code.

    close waits for the subprocess and sets $?:

    my $pid = open X, '-|', 'echo foo; exit 42' or die $!; my $out = <X>; my $ok = close X; print STDERR "out=$out"; printf STDERR "\$?=%s\n", $? >> 8 unless $ok; __END__ out=foo $?=42

    See close for details.

      Thanks! You really prevented me from inventing a wheel :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://935100]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2015-05-23 13:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    In my home, the TV remote control is ...









    Results (467 votes), past polls