我希望能够打印堆栈跟踪Java的方式在C [英] I want to be able to print stack traces java style in c

查看:126
本文介绍了我希望能够打印堆栈跟踪Java的方式在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,我希望能够打印堆栈跟踪Java的方式在C。我有信号处理程序设置和我得到的堆栈跟踪地址,但我想要的地址转换为函数名。因此,我决定实施的反思。现在我有表如下:{FOO,&安培; FOOBAR,&安培; BAR}。虽然这种解决方案适用于所有平台,这实在是烦人保持最新。是否有另一种方式做到这一点(一说难道不需要手动保养?)

Simple question, I want to be able to print stack traces java style in c. I have the signal handlers set up and I get the stack trace addresses but I want to translate the addresses to the function names. Therefore, I decided to implement reflection. Right now I have tables as follows: {"FOO", &FOO, "BAR", &BAR}. While this solution works for all platforms, it is really annoying to keep up to date. Is there another way to do this (one that wouldnt require manual upkeep?)

推荐答案

我想的 http://www.gnu.org/s/libc/manual/html_node/Backtraces.html 你可以找到这个问题的答案。

I'm think http://www.gnu.org/s/libc/manual/html_node/Backtraces.html you can found answer to this question.

 #include <execinfo.h>
 #include <stdio.h>
 #include <stdlib.h>

 /* Obtain a backtrace and print it to stdout. */
 void
 print_trace (void)
 {
   void *array[10];
   size_t size;
   char **strings;
   size_t i;

   size = backtrace (array, 10);
   strings = backtrace_symbols (array, size);

   printf ("Obtained %zd stack frames.\n", size);

   for (i = 0; i < size; i++)
      printf ("%s\n", strings[i]);

   free (strings);
 }

 /* A dummy function to make the backtrace more interesting. */
 void
 dummy_function (void)
 {
   print_trace ();
 }

 int
 main (void)
 {
   dummy_function ();
   return 0;
 }

有从这个网页例如,请确保您有-rdynamic标志编译它,否则你会得到地址,而不是函数名的回溯:)

there is example from this page, make sure you compile it with -rdynamic flag otherwise you will get backtrack of addresses instead of function names :)

这篇关于我希望能够打印堆栈跟踪Java的方式在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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