C/C++编写的程序,崩溃后有时不能生成core文件(即使设置了ulimited),所以往往不知道发生了什么事情,生产环境根本不允许研发小朋友去调试,日志有时候看不出问题了。(如果生成了core文件,或通过日志能定位到问题所以,则可略过此文章)。
本文章专门针对于没有生成core文件、不能通过日志分析问题的情况
第一步:写一段测试代码吧,main.cpp:
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <ucontext.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <thread>
#include <chrono>
#include <vector>
#include <functional>
#include <iomanip>
#include <mutex>
#include <random>
using namespace std;
void sigsegv_handler(int signum)
{
std::cout<<"catch signal:"<<signum<<endl;
void *buffer[1024*1024*10];
char **strings;
int j,nptrs;
nptrs=backtrace(buffer,1024*1024*10);
cout<<"backtrace returned address:"<<nptrs<<endl;
strings=backtrace_symbols(buffer,nptrs);
if (strings!=NULL)
{
for(j=0;j<nptrs;++j)
{
cout<<strings[j]<<endl;
}
}
free(strings);
}
static void catch_sigsegv()
{
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler=sigsegv_handler;
action.sa_flags=SA_NODEFER|SA_RESETHAND;
if (sigaction(SIGSEGV, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGFPE, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGINT, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGILL, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGTERM, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGABRT, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
if (sigaction(SIGSEGV, &action, NULL) != 0) { cout<<"sig_action error"<<endl; }
}
std::mutex m_mutex;
void *thread_entry(int thread_index)
{
unsigned long index=0;
std::default_random_engine e;
e.seed(thread_index);
while(true){
auto random_value=e();
if(random_value%123==0){
int *p=nullptr;
*p=10;
}
{
auto t=std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::lock_guard<std::mutex> lock(m_mutex);
std::cout<<"thread_index["<<thread_index<<"]:id["<<std::this_thread::get_id()<<"]:["<<std::put_time(std::localtime(&t), "%Y-%m-%d %X")<<"]:"<<++index<<":random_value="<<random_value<<std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return nullptr;
}
int main(int argc,char *argv[])
{
//catch_sigsegv();
std::vector<std::thread> thread_vector;
for(int i=0;i<10;++i){
thread_vector.push_back(std::move(std::thread(std::bind(thread_e