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

最后都变了- 提交于 2019-12-19 03:13:33

问题


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?


回答1:


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

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




回答2:


The child might not even have gotten to call exit. As such, $? 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 more clearly in system's documentation.



来源:https://stackoverflow.com/questions/2909011/why-is-perls-returning-the-wrong-value-for-the-exit-code-of-a-forked-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!