背景
一个C++节点,希望再coredump的时候打印调用堆栈信息而不是直接给出core文件。
实现
使用boost::stacktrace::stacktrace()
展示调用栈,依靠signal
进行捕捉。
代码
#include <iostream>
#include <string>
#include <vector>
#include <boost/stacktrace.hpp>
#include <signal.h>
class Base
{
public:
void GetVec()
{
std::cout << vec.front() << std::endl;
}
private:
std::vector<int> vec{};
};
void handler(int sig)
{
::signal(sig, SIG_DFL); // exit normally
std::cout << boost::stacktrace::stacktrace() << std::endl;
}
int main()
{
signal(SIGSEGV, &handler);
Base b;
b.GetVec();
return 0;
}
效果
在线运行https://godbolt.org/z/Txx4KTMqE
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 139
Program terminated with signal: SIGSEGV
0# handler(int) in ./output.s
1# 0x00007F1B86642520 in /lib/x86_64-linux-gnu/libc.so.6
2# Base::GetVec() in ./output.s
3# main in ./output.s
4# 0x00007F1B86629D90 in /lib/x86_64-linux-gnu/libc.so.6
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start in ./output.s
注意
这里有个细节,signal handler 需要是一个信号安全的函数。
比如在signal handler一般是不能做打印的(非信号安全)。
如果想在收到信号后做非信号安全的处理,可参考signal fd
或另起一个线程配合信号安全的通知机制”。
SIG_DFL
的意思是系统再走一下对这个信号的默认处理流程。
举例,对于segment fault,系统的默认处理流程是生成coredump。
简单来说不要忘记调用系统默认的SIG_DFL
否则程序无法自动退出。