1. 程式人生 > >backtrace和backtrace_symbols函式的使用

backtrace和backtrace_symbols函式的使用

在看libdrm庫函式的時候想看看哪些函式呼叫了drmIoctl函式
對drmIoctl做了簡單修改,呼叫了print_trace函式

/**
 * Call ioctl, restarting if it is interupted
 */
int
drmIoctl(int fd, unsigned long request, void *arg)
{
    int ret;


    print_trace();


    do {
        ret = ioctl(fd, request, arg);
    } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
    return
ret; }
#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); }

下面是執行的效果
這裡寫圖片描述

使用時要先設定好庫的路徑,使用如下命令

export LD_RUN_PATH=/usr/local/lib;
或者
export LD_LIBRARY_PATH=/usr/local/lib
編譯命令:
gcc -o test opengl1.cpp -lGL -lglut -ldrm

參考:
/*
Libraries have been installed in:
/usr/local/lib

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the ‘-LLIBDIR’
flag during linking and do at least one of the following:
- add LIBDIR to the ‘LD_LIBRARY_PATH’ environment variable
during execution
- add LIBDIR to the ‘LD_RUN_PATH’ environment variable
during linking
- use the ‘-Wl,-rpath -Wl,LIBDIR’ linker flag
- have your system administrator add LIBDIR to ‘/etc/ld.so.conf’

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.

*/
libc庫函式手冊
https://www.gnu.org/software/libc/manual/html_node/Backtraces.html