Linux程序异常退出打印调用堆栈
/* * 程序异常终止时打印异常程序调用堆栈 * gcc -g -rdynamic BackTraceTest.c -o BackTraceTest * * 运行程序出现错误: * System error, Stack trace: * 0 ./BackTraceTest(SystemErrorHandler+0x77) [0x40095b] * 1 /lib64/libc.so.6() [0x3a4fe326b0] * 2 ./BackTraceTest(Fun1+0x10) [0x400a10] * 3 ./BackTraceTest(Fun+0xe) [0x400a23] * 4 ./BackTraceTest(main+0x37) [0x400a5c] * 5 /lib64/libc.so.6(__libc_start_main+0xfd) [0x3a4fe1ed5d] * 6 ./BackTraceTest() [0x400829] * Segmentation fault (core dumped) * * gdb打印错误行信息 * gdb BackTraceTest * (gdb) info line *0x400a10 * Line 66 of "BackTraceTest.c" starts at address 0x400a0c <Fun1+12> and ends at 0x400a13 <Fun1+19>. * (gdb) list *0x400a10 * 0x400a10 is in Fun1 (BackTraceTest.c:66). * warning: Source file is more recent than executable. * 61 } * 62 * 63 void Fun1() * 64 { * 65 char *p=NULL; * 66 *p = 'A'; * 67 } * 68 * 69 void Fun() * 70 { * * * addr2line 定位程序地址对应的源代码位置 * addr2line -e BackTraceTest -i 0x400a10 * /home/cyf/workspace/BackTraceTest/BackTraceTest.c:66 * */ #include<stdio.h> #include<stdlib.h> #include<signal.h> #include<string.h> #include<execinfo.h> void SystemErrorHandler(int signum) { const int len=1024; void *func[len]; size_t size; int i; char **funs; signal(signum,SIG_DFL); size=backtrace(func,len); funs=(char**)backtrace_symbols(func,size); fprintf(stderr,"System error, Stack trace:\n"); for(i=0;i<size;++i) fprintf(stderr,"%d %s \n",i,funs[i]); free(funs); //exit(1); } void Fun1() { char *p=NULL; *p = 'A'; } void Fun() { Fun1(); } int main(const int argc,const char* argv[]) { signal(SIGSEGV,SystemErrorHandler); //Invaild memory address signal(SIGABRT,SystemErrorHandler); // Abort signal Fun(); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。