程式語言 - GNU - C/C++ - Backtrace



參考資訊:
https://stackoverflow.com/questions/6934659/how-to-make-backtrace-backtrace-symbols-print-the-function-names

main.c

#include <execinfo.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void bt(void)
{
    int s = 0;
    int fd = -1;
    void *b[255] = {0};

    fd = open("bt.txt", O_CREAT | O_WRONLY, 0755);
    if (fd > 0) {
        s = backtrace(b, 255);
        backtrace_symbols_fd(b, s, fd);
        close(fd);
    }
}

void test(void)
{
    bt();
}

int main(int argc, char **argv)
{
    test();
}

編譯、執行

$ gcc main.c -o main
$ ./main
$ cat bt.txt
  ./main(bt+0x68)[0x5559615fd1cd]
  ./main(test+0x9)[0x5559615fd1fd]
  ./main(main+0x14)[0x5559615fd214]
  /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb)[0x7f6301d8409b]
  ./main(_start+0x2a)[0x5559615fd0aa]