0

I am executing shell command using perl using open 3

   local ( *HANDLE_IN, *HANDLE_OUT, *HANDLE_ERR );

    my $pid = open3( *HANDLE_IN, *HANDLE_OUT, *HANDLE_ERR, @cmd_args ); 

where @cmd_args = my shell command

My shell returns below exit codes

0: command executed successfully

>0: error in executing the command

How can i capture the exit code from shell in my perl?

2 Answers 2

5

It's easy, just look at the good old perldoc:

$pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR,
    'some cmd and args', 'optarg', ...);

my($wtr, $rdr, $err);
use Symbol 'gensym'; $err = gensym;
$pid = open3($wtr, $rdr, $err,
    'some cmd and args', 'optarg', ...);

waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

$child_exit_status then contains the status of the program executed.

Another method to use is ${^CHILD_ERROR_NATIVE} which I'm using especially when executing external commands via backticks:

my $fancyresult = `ls -lsahR /`;

if (${^CHILD_ERROR_NATIVE} != 0) {
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

You can just as easily use $? for backticks too.
@constantlearner The command you are calling is probably not finished.
2

You need to eventually reap the child using wait or waitpid. When you do, $? will be set as follows.

waitpid($pid, 0);
die "Can't waitpid: $!" if $? < 0;
die "Child killed by signal ".( $? & 0x7F ) if $? & 0x7F;
die "Child returned error ".( $? >> 8 ) if $? >> 8;
print "Child ran successfully!\n";  # if $? == 0

1 Comment

After adding these lines my script hangs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.