Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Perl's $? returning the wrong value for the exit code of a forked process?

Tags:

perl

waitpid

Consider this trivial example of fork()ing then waiting for a child to die in Perl:

#!/usr/bin/perl

use strict;
use warnings;

if (fork() == 0) {
        exit(1);
}

waitpid(-1,0);

print $?;

Running the script on Solaris 10 I get this result:

$ perl test.pl
256

I suspect the values of are being shifted upwards because when I do exit(2) in the child, the output becomes 512.

I can't seem to find this documented in perl's waitpid. Is this a bug on my system or am I doing something wrong?

like image 644
Mike Avatar asked May 25 '10 22:05

Mike


People also ask

How does exit function work in Perl?

Perl exit | How does exit Function work in Perl with example? Perl exit work assesses the articulation passed to it and ways out from the Perl mediator while restoring the incentive as the leave esteem. The exit () work doesn’t generally exit quickly yet calls the end schedules before it ends the program.

How do I run a Perl program?

The ordinary method to run a Perl program is by making it legitimately executable, or, in all likelihood, by passing the name of the source document as a contention on the order line. Determined line by line by means of – e or – E turns on the order line.

What is the default value of the exit () function?

The exit () function does not always exit immediately but calls the end routines before it terminates the program. If no expression is passed to the exit function then a default value 0 is returned.


1 Answers

It's documented in the $? section of the perlvar man page.

i.e. the real exit code is $? >> 8.

like image 129
Sean Avatar answered Oct 14 '22 04:10

Sean