在头文件"execinfo.h"中声明了三个函数用于获取当前线程的函数调用堆栈。
#include <execinfo.h>
int backtrace(void **buffer, int size);
char **backtrace_symbols(void *const *buffer, int size);
void backtrace_symbols_fd(void *const *buffer, int size, int fd);
man 帮助:
DESCRIPTION
A backtrace is the series of currently active function calls for the program. Each item in the array pointed to by buffer is of type void *, and is the return address from the corresponding stack frame. The size argument specifies the maximum number of addresses that can be stored in buffer. If the backtrace is larger than size, then the addresses corresponding to the size most recent function calls are returned; to obtain the complete backtrace, make sure that buffer and size are large enough. Given the set of addresses returned by backtrace() in buffer, . The size argument specifies the number of addresses in buffer. The symbolic representation of each address consists of the function name (if this can be determined), a hexadecimal offset into the function, and the actual return address (in hexadecimal). backtrace_symbols_fd() takes the same buffer and size arguments as backtrace_symbols(), but instead of returning an array of strings to the caller,. backtrace_symbols_fd() does not call malloc(3), and so can be employed in situations where the latter function might fail.
#include <execinfo.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void myfunc3(void) { int j, nptrs; #define SIZE 100 void *buffer[100]; char **strings; nptrs = backtrace(buffer, SIZE); printf("backtrace() returned %d addresses\n", 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\n", strings[j]); free(strings); } static void /* "static" means don't export the symbol... */ myfunc2(void) { myfunc3(); } void myfunc(int ncalls) { if (ncalls > 1) myfunc(ncalls - 1); else myfunc2(); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "%s num-calls\n", argv[0]); exit(EXIT_FAILURE); } myfunc(atoi(argv[1])); exit(EXIT_SUCCESS); }
结果:
总结:使用以下几个函数既可完成堆栈信息的打印
int backtrace (void **buffer, int size)
char ** backtrace_symbols (void *const *buffer, int size)
char* abi::__cxa_demangle
(
const char * mangled_name,
char * output_buffer,
size_t * length,
int * status
)
1. backtrace可以在程序运行的任何地方被调用,返回各个调用函数的返回地址,可以限制最大调用栈返回层数。
2. 在backtrace拿到函数返回地址之后,backtrace_symbols可以将其转换为编译符号,这些符号是编译期间就确定的
3. 根据backtrace_symbols返回的编译符号,abi::__cxa_demangle可以找到具体地函数方法