- 论坛徽章:
- 0
|
连接十分不错~~ 刚刚的~~ ![](static/image/smiley/default/em03.gif) - With the GNU C Library, you can use the backtrace module. Here is an example for that:
- #include <stdio.h>
- #include <execinfo.h>
- #include <stdlib.h>
- void handler(char *caller) {
- void *array[10];
- size_t size;
- printf("Stack Trace Start for %s\n",caller);
- size = backtrace(array, 10);
- backtrace_symbols_fd(array, size, 2);
- printf("Stack Trace End\n");
- }
- void car() {
- handler("car()");
- printf("Continue Execution");
- }
- void baz() {car(); }
- void bar() { baz(); }
- void foo() { bar(); }
- int main(int argc, char **argv) {
- foo();
- }
- compile with -g -rdynamic compiler option to load the symbols
- gcc -g -rdynamic Test1.c -o Test
- You will see an output similar to
- Stack Trace Start for car()
- ./Test(handler+0x2d)[0x80486f1]
- ./Test(car+0x12)[0x804872e]
- ./Test(baz+0xb)[0x8048747]
- ./Test(bar+0xb)[0x8048754]
- ./Test(foo+0xb)[0x8048761]
- ./Test(main+0xb)[0x804876e]
- /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x126e37]
- ./Test[0x8048631]
- Stack Trace End
- Continue Execution in car
- You can write this handler function and call from anywhere in your program at any number of time. Remember to increase the array size as required.
复制代码 |
|