如何在没有 pstack 和 gdb 的情况下获取线程堆栈信息

How to obtain thread stack information WITHOUT pstack and gdb

有没有办法在一些非常小的 linux 上获取有关程序卡住的原因的信息,当无法插入任何日志并且没有 pstack 和 gdb 时?

我的建议是:

  1. 能够在您自己的程序中检索操作并打印堆栈跟踪
  2. 为你的进程安装一个信号处理程序(比如,SIGUSR1)
  3. 在程序卡住时向您的程序发送信号 - 控制将移至信号处理程序(假设您没有屏蔽信号)。

现在 (2.) 和 (3.) 非常简单。对于 (3.),它是 kill -USR1 1234(对于 ID 为 1234 的进程)。对于 (2.),它是:

#include <signal.h>
typedef void (*sighandler_t)(int);
sighandler_t sigset(int sig, sighandler_t disp);

(阅读 man sigset 了解详情)。

至于(1.),以前比较棘手,现在基本解决了:

Boost StackTraceCode | Documentation

它将尽最大可能获取尽可能多的堆栈跟踪信息。一个简单的使用示例:

#include <iostream>
#include <boost/stacktrace.hpp>

// ... somewhere inside the `bar(int)` function that is called recursively:
std::cout << boost::stacktrace::stacktrace();

可能会产生以下输出:

0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start

注意: StackTrace 是 Boost 的最新补充(截至 2017 年 8 月);如果您的 Boost 版本不够新,您可以考虑单独获取它。