陷阱无法捕获SIGSEGV [英] trap fails to catch SIGSEGV

查看:63
本文介绍了陷阱无法捕获SIGSEGV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此脚本测试陷阱:

I'm using this script to test trap:

#!/bin/bash

trap "echo segfault!" SIGSEGV
g++ forever.cpp
./a.out

并且 forever.cpp 只是运行一个递归函数:

And forever.cpp just runs a recursive function:

void forever(){
    forever();
}
int main(){
    forever();
}

但是它会给出 Segmentation错误:11 ,而不是打印 segfault .我不确定为什么.

However it gives Segmentation fault: 11 instead of printing segfault. I'm not sure why.

推荐答案

trap 语句将捕获 bash 而不是其子级接收的信号.子级收到段错误,将以适当的退出代码退出.因此,您应该检查子进程的退出代码.从此处可以看到,退出代码是128 +信号号. SEGV 为11(请参见 man signal ),因此您将获得139的退出代码.因此只需针对139测试 $?,您便可以已经完成了.

The trap statement traps signals received by bash, not its children. The child receives the segfault and will be exiting with an appropriate exit code. You should therefore check the exit code from the child process. As you can see from here, the exit code is 128+signal number. SEGV is 11 (see man signal), so you will get an exit code of 139. So simply test $? against 139, and you have done.

这篇关于陷阱无法捕获SIGSEGV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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