以下是注定要崩溃的C代码:
#include<stdio.h> #include<stdlib.h> int main() { char *p = NULL; printf("Value at P: %c\n",*p); return 0; }
当我编译并运行它(RH4机器与gcc 4.5.2)时,它可预测地给出了一个分段错误:
% ./a.out Segmentation fault % echo $status 139
如果我使用Perl v5.8.5运行它,会发生这种情况:
% perl -e 'system("./a.out") and die "Status: $?"' Status: 11 at -e line 1.
Thus,the exit value of the subprocess is really
($?>> 8 )
,and$? &
gives which signal,if any,the process died from,and
127$? & 128
reports whether there was a core dump.
11>> 8是0,11& 127是11.
解决方法
阅读系统文档可能会回答您的问题:
system('a.out'); 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; }
输出:
child died with signal 11,without coredump
shell只是以不同的方式对状态中的信号进行编码:139 – 128 = 11.例如,man bash说:
The return value of a simple command is its exit status,or 128+n if the command is terminated by signal n.