美文网首页
linux下C应用程序打印调用栈

linux下C应用程序打印调用栈

作者: itsenlin | 来源:发表于2023-03-16 15:00 被阅读0次

    使用GCC编译的C应用程序,如果想在某个接口中打印调用栈,可以使用gcc的backtraces特性

    Backtraces说明中有一个例子,代码如下:

    #include <execinfo.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    /* Obtain a backtrace and print it to stdout. */
    void
    print_trace (void)
    {
      void *array[10];
      char **strings;
      int size, i;
    
      size = backtrace (array, 10);
      strings = backtrace_symbols (array, size);
      if (strings != NULL)
      {
    
        printf ("Obtained %d 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;
    }
    

    直接通过gcc来编译运行,结果如下:

    itsenlin@itsenlin-virtual-machine:~/code/test$ gcc -o backtr backtr.c
    itsenlin@itsenlin-virtual-machine:~/code/test$ ./backtr
    Obtained 6 stack frames.
    ./backtr(+0x1215) [0x559a1a0b2215]
    ./backtr(+0x12b1) [0x559a1a0b22b1]
    ./backtr(+0x12c1) [0x559a1a0b22c1]
    /lib/x86_64-linux-gnu/libc.so.6(+0x29d90) [0x7f779d629d90]
    /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80) [0x7f779d629e40]
    ./backtr(+0x1125) [0x559a1a0b2125]
    itsenlin@itsenlin-virtual-machine:~/code/test$
    
    

    如果想显示函数名,还需要在编译时添加-rdynamic选项,如下

    itsenlin@itsenlin-virtual-machine:~/code/test$ gcc -o backtr backtr.c -rdynamic
    itsenlin@itsenlin-virtual-machine:~/code/test$ ./backtr
    Obtained 6 stack frames.
    ./backtr(print_trace+0x2c) [0x560984d66215]
    ./backtr(dummy_function+0xd) [0x560984d662b1]
    ./backtr(main+0xd) [0x560984d662c1]
    /lib/x86_64-linux-gnu/libc.so.6(+0x29d90) [0x7f860a029d90]
    /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80) [0x7f860a029e40]
    ./backtr(_start+0x25) [0x560984d66125]
    itsenlin@itsenlin-virtual-machine:~/code/test$ vim backtr.c
    itsenlin@itsenlin-virtual-machine:~/code/test$
    

    相关文章

      网友评论

          本文标题:linux下C应用程序打印调用栈

          本文链接:https://www.haomeiwen.com/subject/pqcdrdtx.html