Hailiang Zhang Hailiang Zhang - 3 months ago 7
Perl Question

Why is the result of system() in Perl not the exact exit code of my script?

I have the following perl script (

test.pl
):

my $exit_code = system('./test.py');
print $exit_code."\n";


that is trying to capture the exit code from a python executable (
test.py
):

#!/bin/env python
import sys
sys.exit(2)


Directly running python executable returns 2, which is what I expected:

> ./test.py
> echo $?
2


However, running perl returns something different:

> perl test.pl
512


Why did perl capture a different exit code from python?

Answer

The child might not even have gotten to call exit. As such, system's returns value (aka $?) packs more information than just the exit parameter.

if    ( $? == -1  ) { die "Can't launch child: $!\n"; }
elsif ( $? & 0x7F ) { die "Child killed by signal ".( $? & 0x7F )."\n"; }
elsif ( $? >> 8   ) { die "Child exited with error ".( $? >> 8 )."\n"; }
else                { print "Child executed successfully\n"; }

This is documented.

Comments