c/c++ 打印调用栈

打印调用栈可以在程序出现死机的时候(如出现 SIGABRT、SIGSEGV等一些信号错误)是很有用的信息,有可能就不需要 core file 来协助排查问题了。通过 man backtrace 可以得到一个例子的源码:

cpp 复制代码
#define SIZE 100
static void backTracePro(void) 
{ 
    int j, nptrs; 
 
    void *buffer[SIZE]; 
    char **strings; 
    nptrs = backtrace(buffer, SIZE);
    printf("****************************************\n");//这行我自己加的
    printf("backtrace() returned %d addresses\n", nptrs); 

    /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) 
     would produce similar output to the following: */ 
    strings = backtrace_symbols(buffer, nptrs); 
    if (strings == NULL) 
    { 
        perror("backtrace_symbols"); 
        exit(EXIT_FAILURE); 
    } 

    for (j = 0; j < nptrs; j++)
    {
        printf("%s\n", strings[j]); 
    }
    
    free(strings); 
}

然后可以把这个函数放在信号回调函数里,所以先需要设置一下信号处理函数,函数:int sigaction (int __sig, const struct sigaction *__restrict __act, struct sigaction *__restrict __oact),

cpp 复制代码
static bool initSignalCallBack() 
{
    struct sigaction sigact;

    memset(&sigact, 0, sizeof(sigact));
    sigact.sa_handler = signalHandler;

    sigemptyset(&(sigact.sa_mask));

    int ret = sigaction(SIGABRT, &sigact, NULL);
	if(0 == ret)
	{
		ret |= sigaction(SIGSEGV, &sigact, NULL);
	}
	else
	{
		strerror(errno);
		return false;
	}
	
	if(ret)
	{
		strerror(errno);
	}
	
	return ret == 0;
}

所以可以把 backTracePro() 放到信号回调函数 signalHandler() 里,看看执行结果:

接下来用 c++filt 解析一下符号就可以看到调用到哪个函数了。

相关推荐
旺小仔.12 分钟前
【数据结构篇】~二叉树(堆)
c语言·数据结构·算法·链表·性能优化
打嗝小狗~35 分钟前
【C语言】深入理解指针3(附转移表源码)
java·c语言·开发语言
红茶川42 分钟前
C++ TinyWebServer项目总结(12. 高性能I/O框架库Libevent)
linux·服务器·c++
这么牛逼的代码我写的1 小时前
Day24 第11站 出发 c++!
开发语言·c++·算法
武昌库里写JAVA2 小时前
golang笔记——Go堆内存管理
c语言·开发语言·数据结构·算法·二维数组
六点半8882 小时前
【C++】类与对象篇四
c++
一只努力学习的Cat.2 小时前
C++:list篇
c++
fpcc2 小时前
软件中的重构
c++·重构
wuziNO_12 小时前
C++ 基础学习
c++·学习·算法
weixin_711800883 小时前
C语言重难点总结(2)-指针操作与结构体、动态内存
c语言·开发语言