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

相关推荐
逆小舟1 小时前
【Linux】人事档案——用户及组管理
linux·c++
l1t1 小时前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t3 小时前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
风中的微尘6 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某6 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程6 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_7 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan7 小时前
【C++】类和对象1
java·开发语言·c++
阿昭L8 小时前
MFC仿真
c++·mfc
Gu_shiwww9 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步