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 解析一下符号就可以看到调用到哪个函数了。

相关推荐
_F_y7 小时前
MySQL用C/C++连接
c语言·c++·mysql
兩尛7 小时前
c++知识点2
开发语言·c++
xiaoye-duck7 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
BackCatK Chen7 小时前
C语言学习栏目目录
c语言·保姆级教程·c语言入门·c语言学习栏目目录
Azure_withyou8 小时前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月8 小时前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
极客数模9 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
L_09079 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
请注意这个女生叫小美12 小时前
C语言 斐波那契而数列
c语言
Legendary_00812 小时前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言