对于Linux,Mac OS X,android,如果你使用gcc或者编译器使用glibc,你能使用backtrace()函数来打印堆栈信息,backtrace在execinfo.h中申明。
这里有一个例子,安装一个SIGSEGV处理用来打印stacktrace到stderr。baz()函数引发一个异常。
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig) {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
void baz() {
int *foo = (int*)-1; // make a bad pointer
printf("%d\n", *foo); // causes segfault
}
void bar() { baz(); }
void foo() { bar(); }
int main(int argc, char **argv) {
signal(SIGSEGV, handler); // install our handler
foo(); // this will call foo, bar, and baz. baz segfaults.
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
编译使用-g -rdynamic取得符合信息。
$ gcc -g -rdynamic ./test.c -o test
- 1
这里例子执行输出:
$ ./test
Error: signal 11:
./test(handler+0x19)[0x400911]
/lib64/tls/libc.so.6[0x3a9b92e380]
./test(baz+0x14)[0x400962]
./test(bar+0xe)[0x400983]
./test(foo+0xe)[0x400993]
./test(main+0x28)[0x4009bd]
/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]
./test[0x40086a]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
关于android如何实现
https://bitbucket.org/xg/android-game-base/src/c0d969d44a55a76a6fd2677ab5bb434a6dac3bd3/src/com/gmail/whittock/tom/Util/CrashHandler.java?at=default
https://bitbucket.org/xg/android-game-base/src/c0d969d44a55/jni/NativeActivityJNI.cpp#cl-40
这里有一个android下的开源实现
https://github.com/SalomonBrys/__deprecated__Native-Crash-Handler
这个版本在native代码奔溃后,俘获并且发送一个java异常。这样ACRA可以进行统一的报告出来。
转自:http://blog.csdn.net/john_crash/article/details/46971535