从信号处理程序打印堆栈跟踪 [英] Printing stack trace from a signal handler

查看:34
本文介绍了从信号处理程序打印堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从在 Linux 上运行的 64 位多线程 C++ 应用程序的信号处理程序打印堆栈跟踪.虽然我找到了几个代码示例,但没有一个可以编译.我的阻塞点是从 ucontext_t 结构中获取调用者的(生成信号的点)地址.我能找到的所有信息都指向 EIP 寄存器,即 ucontext.gregs[REG_EIP] 或 ucontext.eip.看起来它们都是 x86 特定的.我需要适用于 Intel 和 AMD CPU 的 64 位兼容代码.有人可以帮忙吗?

I need to print stack trace from a signal handler of 64-bit mutli-threaded C++ application running on Linux. Although I found several code examples, none of them compiles. My blocking point is getting the caller's (the point where the signal was generated) address from the ucontext_t structure. All of the information I could find, points to the EIP register as either ucontext.gregs[REG_EIP] or ucontext.eip. It looks like both of them are x86-specific. I need 64-bit compliant code for both Intel and AMD CPUs. Can anybody help?

推荐答案

有一个 glibc 函数 backtrace.手册页列出了调用示例:

there is a glibc function backtrace. The man page lists an example the the call:

#define SIZE 100
void myfunc3(void) {
       int j, nptrs;

       void *buffer[100];
       char **strings;

       nptrs = backtrace(buffer, SIZE);
       printf("backtrace() returned %d addresses
", 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
", strings[j]);

       free(strings);
   }

有关更多上下文,请参阅手册页.

See the man page for more context.

很难判断这是否真的保证可以从信号处理程序中工作,因为 posix 仅列出了一些保证工作的可重入函数.请记住:信号处理程序可能会被调用,而您的进程的其余部分正处于 malloc 调用的中间.

it's difficult to tell if this really is guaranteed to work from a signal handler, since posix lists only a few reentrant functions that are guaranteed to work. Remember: a signal handler may be called while the rest of your process is right in the middle of an malloc call.

我的猜测是,这通常有效,但有时可能会失败.对于调试来说,这可能已经足够了.

My guess is, that this usually works, but it may fail from time to time. For debugging this may be good enough.

这篇关于从信号处理程序打印堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆