【Linux】直接打印堆栈调试信息
1,目前最简单的办法时gdb,运行调试.
https://www.bogotobogo.com/Linux/debugging_gdb.php
2,使用backtrace
linux journalctl 命令也可以查看.或直接输入代码中.
https://cloud.tencent.com/developer/article/2286090?areaSource=102001.7&traceId=2yACtnVrq4Oa5oN_wA9RT
使用 signal(signum,SIG_DFL); size = backtrace(array,100); strings = (char**)backtrace_symbols(array,size);
#include <stdio.h> #include <signal.h> //信号钩子函数,获取栈信息,然后打印 void handle_segv(int signum){ void *array[100]; size_t size; char **strings; size_t i; signal(signum,SIG_DFL); size = backtrace(array,100); strings = (char**)backtrace_symbols(array,size); fprintf(stderr,"Launcher received SIG:%d Stack trace:\n",signum); for(i = 0;i <size;i++){ fprintf(stderr,"%d %s\n",i,strings[i]); } free(strings); } int func(int* p){ int y = *p; return y; } int main(void){ int *p = NULL; signal(SIGSEGV,handle_segv); signal(SIGABRT,handle_segv); return func(p); }
gcc -g demo.c -o demo