我希望能够打印堆栈跟踪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 :)