PerlDuck
PerlDuck

Reputation: 5730

Is the value returned by system() the same as "$?"?

When I do system() calls in Perl, I usually inspect the return code according to the perldocs. Well, I thought so. Most of the time $rc!=0 is sufficient for me. Recently I helped two people here which had trouble with system() calls when running their .cgi scripts under apache. I instructed them to examine the $rc of

my $rc = system(...);

and linked them to the system() docs. Then I looked closer and noticed the docs aren't really talking about the $rc but instead about $? and I felt a bit embarassed and the following question arose:

Is there a difference between:

system(...);
if ($? == -1) {
    print "failed to execute: $!\n";
}
elsif ($? & 127) {
    printf "child died with signal %d, %s coredump\n",
        ($? & 127),  ($? & 128) ? 'with' : 'without';
}
else {
    printf "child exited with value %d\n", $? >> 8;
}

and

my $rc = system(...);
if ($rc == -1) {
    print "failed to execute: $!\n";
}
elsif ($rc & 127) {
    printf "child died with signal %d, %s coredump\n",
        ($rc & 127),  ($rc & 128) ? 'with' : 'without';
}
else {
    printf "child exited with value %d\n", $rc >> 8;
}

Or, for short, is $rc equal to $? for system()?

I looked through the docs of system, wait, and $? but it's not quite clear to me. Did I do wrong for the last 15 years by using $rc?

Upvotes: 15

Views: 223

Answers (1)

Hunter McMillen
Hunter McMillen

Reputation: 61510

Yes, the return value of system should equal $?.

However since $? does not only apply to system calls and $? is a global variable, it could be overwritten by other actions that are occurring. From perldoc -v '$?' these include:

$CHILD_ERROR

$?

The status returned by the last pipe close, backtick ("``") command, successful call to "wait()" or "waitpid()", or from the "system()" operator.

It is far safer to store the value immediately then compare:

my $rc = system('ls myfile.txt');
if ( $rc >> 8 != 0 ) {
   # do something because ls exited with an error
}

Upvotes: 11

Related Questions