如何抓住Linux中的分段错误? [英] How to catch segmentation fault in Linux?

查看:190
本文介绍了如何抓住Linux中的分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要捕获第三方库清理操作中的分段错误。这发生有时就在我的程序退出之前,我不能解决这个的真正原因。在Windows编程中,我可以使用__try - __catch来做到这一点。是否有跨平台或平台特定的方式来做同样的?

I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux, gcc.

推荐答案

在Linux上,我们也可以将这些作为例外。

On Linux we can have these as exceptions, too.

通常,当程序执行分段错误时,会发送一个 SIGSEGV 信号。您可以为此信号设置自己的处理程序,并减轻后果。当然,你应该确保你可以从情况中恢复。在你的情况下,我认为你应该调试你的代码。

Normally, when your program performs a segmentation fault, it is sent a SIGSEGV signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead.

返回主题。我最近遇到了简短手册),将此类信号转换为异常,因此您可以编写如下代码:

Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this:

try
{
    *(int*) 0 = 0;
}
catch (std::exception& e)
{
    std::cerr << "Exception catched : " << e.what() << std::endl;
}

在我的x86-64 Gentoo框。它有一个平台特定的后端(借鉴了gcc的java实现),因此它可以在许多平台上工作。它只是支持x86和x86-64开箱即用,但你可以从libjava,它驻留在gcc源。

Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.

这篇关于如何抓住Linux中的分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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