Linux中打印函数堆栈

2014-11-24 08:10:23 · 作者: · 浏览: 2

Linux中打印函数堆栈


mongo源码目录下的util/stacktrace.cpp文件:


// Copyright 2009. 10gen, Inc.



#include "mongo/util/stacktrace.h"


#include
#include
#include
#include
#include
#include


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);
}
}