在編寫穩(wěn)定可靠的軟件服務(wù)時(shí)經(jīng)常用到輸出堆棧信息,以便用戶/開發(fā)者獲取準(zhǔn)確的運(yùn)行信息。常用在日志輸出,錯(cuò)誤報(bào)告,異常檢測。
在Linux有比較簡便的函數(shù)獲取堆棧信息:
#include <stdio.h>#include <execinfo.h>#include <signal.h>#include <stdlib.h>#include <unistd.h>void handler(int sig) { void *array[5]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 5); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); char** msgs = backtrace_symbols(array, size); for(int i=1;i<size && msgs[i];++i) printf("[%d] %s\n", i, msgs[i]); 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.}
以上代碼從參考的stacko