歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Linux中打印函數堆棧

Linux中打印函數堆棧

mongo源碼目錄下的util/stacktrace.cpp文件:

// Copyright 2009. 10gen, Inc.


#include "mongo/util/stacktrace.h"

#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <execinfo.h>

namespace mongo {
  static const int maxBackTraceFrames = 20;

  void printStackTrace(std::ostream& os) {
    void *b[maxBackTraceFrames];

    int size = ::backtrace(b, maxBackTraceFrames);
    for (int i = 0; i < size; ++i) {
      os << std::hex << b[i] << std::dec << ' ';
    } 
    os << std::endl;

    char** strings;
    strings = ::backtrace_symbols(b, size);
    for (int i = 0; i < size; ++i) {
      os << ' ' << strings[i] << '\n';
    } 
    os.flush();
    ::free(strings);
  }
}

Copyright © Linux教程網 All Rights Reserved