Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

in perl, how do we detect a segmentation fault in an external command

Following is C code that is destined to crash:

#include<stdio.h>
#include<stdlib.h>

int main() {
    char *p = NULL;
    printf("Value at P: %c
", *p);
    return 0;
}

When I compile and run it (RH4 machine with gcc 4.5.2), it predictably gives a segmentation fault:

%  ./a.out
Segmentation fault

%  echo $status
139

If I run it with Perl v5.8.5, this happens:

%  perl -e 'system("./a.out") and die "Status: $?"'
Status: 11 at -e line 1.

The perlvar documentation for $? says that

Thus, the exit value of the subprocess is really ($?>> 8 ), and $? & 127 gives which signal, if any, the process died from, and $? & 128 reports whether there was a core dump.

11 >> 8 is 0, and 11 & 127 is 11.

Why the different exit statuses? If we cannot depend on the exit status, what should be the way to detect segmentation fault in an external command?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading the documentation for system might answer your question:

system('a.out');

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

Output:

child died with signal 11, without coredump

The shell just encodes the signal in the status in a different way: 139 - 128 = 11. For example, man bash says:

The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...