在 C++ 中捕获 Segfault 或任何其他错误/异常/信号,例如在 Java 中捕获异常

我基于一个有缺陷的开源库编写了一个 Linux 程序.这个库有时会触发我无法控制的段错误.当然,一旦库出现段错误,整个程序就会死掉.但是,即使库有段错误,我也必须确保我的程序继续运行.这是因为我的程序有点像服务器",它至少需要告诉客户发生了一些不好的事情并从错误中恢复,而不是退缩......有什么办法吗?

I wrote a Linux program based on a buggy open source library. This library sometimes triggers segfaults that I cannot control. And of course once the library has segfaults, the entire program dies. However, I have to make sure my program keeps running even if the library has segfaults. This is because my program sort of serves as a "server" and it needs to at least tell the clients something bad happened and recover from the errors, rather than chicken out... Is there any way to do that?

我理解在 Java 中只需要捕获一个异常.但是 C++ 是如何处理这个问题的呢?

I understand in Java one just needs to catch an exception. But how does C++ handle this?

[更新]我知道 C++ 中也有异常处理,但是 Segfault 不是异常,是吗?我认为发生段错误时不会抛出任何东西.你必须明确地抛出"一些东西来使用 try.... catch.... 据我所知.

[UPDATE]I understand there is also exception handling in C++, but Segfault is not an exception, is it? I don't think anything is thrown when segfault happens. You have to explicitly "throw" something to use try.... catch.... as far as I know.

非常感谢,我对 C++ 很陌生.

Thanks so much, I am quite new to C++.

推荐答案

你不能可靠在分段违规后恢复执行.如果您的程序必须保持运行,请在单独的进程中隔离有问题的库并通过管道与其通信.当它发生分段违规时,您的程序会注意到关闭的管道.

You cannot reliably resume execution after a segmentation violation. If your program must remain running, fence off the offending library in a separate process and communicate with it over a pipe. When it takes a segmentation violation, your program will notice the closed pipe.

相关文章