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

前端 未结 2 1742
一向
一向 2021-01-12 14:04

Following is C code that is destined to crash:

#include
#include

int main() {
    char *p = NULL;
    printf(\"Value at P: %c         


        
2条回答
  •  盖世英雄少女心
    2021-01-12 15:06

    Reading the documentation for system might answer your question:

    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;
    }
    

    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.

提交回复
热议问题