如何在 C++ 中获取未处理异常的原始堆栈跟踪?

问题描述

之前有人问过这个问题,但那里提出的解决方案对我不起作用。问题是当发生未处理的异常并调用 std::terminate 时,抛出异常的原始堆栈跟踪消失了。我们怎样才能得到它? 这是一个简单的测试应用程序,其中子线程抛出异常并调用 std:: terminate。核心文件不显示原始堆栈跟踪。

我在下面尝试过,它们都不起作用-- i) std::set_terminate(myhandler) -- myhandler 按预期调用,但这不会影响堆栈展开。 ii) 使用 -fno-exceptions 编译——没有效果,可能是因为异常是从 std 库中抛出的。

任何建议将不胜感激!

$ cat thread.cpp
#include <utility>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <vector>
void f1()
{
    for (int i = 0; i < 10; ++i) {
        std::cout << "Thread 1 executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        // !!! create an exception,how to get the stack trace here.
        std::vector<int> vec;
        vec.reserve(-1);
    }
}
int main()
{
    std::thread t1(f1);
    t1.join();
    std::cout << "Done "  << '\n';
}
$ g++ -g thread.cpp -pthread
$ ./a.out
Thread 1 executing
terminate called after throwing an instance of 'std::length_error'
  what():  vector::reserve
Aborted (core dumped)

$gdb a.out core
...
    Core was generated by `./a.out'.
    Program terminated with signal SIGABRT,Aborted.
    #0  0x00007f7e13084277 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
    56    return INLINE_SYSCALL (tgkill,3,pid,selftid,sig);
    [Current thread is 1 (Thread 0x7f7e1304d700 (LWP 106036))]
    Missing separate debuginfos,use: debuginfo-install libgcc-4.8.5-28.el7_5.1.x86_64 libstdc++-4.8.5-28.el7_5.1.x86_64
    (gdb) thread apply all bt
    Thread 2 (Thread 0x7f7e14054740 (LWP 106035)):
    #0  0x00007f7e13423f97 in pthread_join (threadid=140179461691136,thread_return=0x0) at pthread_join.c:92
    #1  0x00007f7e13c03e37 in std::thread::join() () from /lib64/libstdc++.so.6
    #2  0x0000000000400f8f in main () at thread.cpp:22
    Thread 1 (Thread 0x7f7e1304d700 (LWP 106036)):
    #0  0x00007f7e13084277 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
    #1  0x00007f7e13085968 in __GI_abort () at abort.c:90
    #2  0x00007f7e13baf7d5 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
    #3  0x00007f7e13bad746 in ?? () from /lib64/libstdc++.so.6
    #4  0x00007f7e13bad773 in std::terminate() () from /lib64/libstdc++.so.6
    #5  0x00000000004023de in execute_native_thread_routine ()
    #6  0x00007f7e13422e25 in start_thread (arg=0x7f7e1304d700) at pthread_create.c:308
    #7  0x00007f7e1314cbad in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:113

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)