在 perl 中,我们如何检测外部命令中的分段错误 [英] in perl, how do we detect a segmentation fault in an external command

查看:41
本文介绍了在 perl 中,我们如何检测外部命令中的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是注定会崩溃的 C 代码:

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\n", *p);
    return 0;
}

当我编译并运行它(带有 gcc 4.5.2 的 RH4 机器)时,它可以预见地给出一个分段错误:

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

如果我用 Perl v5.8.5 运行它,会发生这种情况:

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.

$?perlvar 文档说

因此,子进程的退出值真的是($?>>8),而$?&127 给出了进程因哪个信号而死亡,以及 $?&128报告是否有核心转储.

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 为 011 &12711.

为什么退出状态不同?如果我们不能依赖退出状态,那么在外部命令中检测分段错误的方法应该是什么?

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?

推荐答案

阅读 system 的文档可能会回答你的问题:

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

输出:

child died with signal 11, without coredump

shell 只是以不同的方式对状态中的信号进行编码:139 - 128 = 11.例如,man bash 说:

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

简单命令的返回值是它的退出状态,如果命令被信号 n 终止,则返回 128+n.

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

这篇关于在 perl 中,我们如何检测外部命令中的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆