检测异常并打印堆栈
2010-12-22 09:28
288 查看
#include <iostream> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <execinfo.h> #include <stdio.h> using namespace std; static void print_stack(void) { void *array[10]; char **strings; int arrsize = backtrace (array, 10); int i; strings = backtrace_symbols (array, arrsize); for (i = 1; i < arrsize; i++) { printf (" --> %s/n", strings[i]); } printf ("/n"); free (strings); } static void sig_handle(int sig) { cout<<"Capture seg fault..."<<endl; print_stack(); exit(0); } class A { public: void get_type() { cout<<"called:"<<m<<endl; } private: int m; }; int entry_func() { try { signal(SIGSEGV,sig_handle); A* ptoA = NULL; ptoA->get_type(); } catch(int) { cout<<"excption... int ..."<<endl; } catch(...) { cout<<"execption..."<<endl; } return 0; } int main() { entry_func(); return 0; }
运行可执行程序时偶尔会遇到段错误,实际上是捕捉到了SIGSEGV信号,然后会打印出熟悉的Segmentation fault...但是又没有其他的信息,很不好调试...因此写个小工具来捕捉段错误的信号,然后注册一个sighandler,来处理,并打印出相应的堆栈...就能马上知道出错的函数的名字了...
哈哈```很方便吧...``
相关文章推荐
- 封装ThreadPoolExecutor 支持打印异常堆栈
- backtrace-----打印进程异常退出时的堆栈信息
- 打印Java异常堆栈信息
- 如何打印Java异常的完整堆栈内容
- MFC异常打印调用堆栈整合SEH异常和日志文件类
- 日志如何打印异常堆栈信息。
- python3中打印异常堆栈信息
- log4j 不打印异常堆栈
- java没有打印异常调用堆栈的问题
- android利用异常打印调用堆栈信息
- backtrace-----打印进程异常退出时的堆栈信息
- Struts2不打印异常堆栈信息
- backtrace-----打印进程异常退出时的堆栈信息
- log4j打印抛出异常时堆栈内容
- 打印java异常堆栈信息到日志文件
- backtrace-----打印进程异常退出时的堆栈信息
- 日志中不打印异常堆栈
- 将Java异常的完整堆栈内容打印到log4j日志
- JVM参数OmitStackTraceInFastThrow:不打印NullPointerException异常堆栈
- Linux程序异常退出打印调用堆栈