C++语言中调用window API函数CreateFile()和MiniDumpWriteDump(),记录程序崩溃时的Dump信息,并保持dump文件,根据dump文件对应的源码工程和.pdb文件,快速的定位到程序崩溃的源码位置
#include "DbgHelp.h"
LONG ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
QString strDumpFolder = QApplication::applicationDirPath() + "\\dump";
QDir dir(strDumpFolder);
if (!dir.exists())
{
dir.mkpath(strDumpFolder);
}
QString strPath = strDumpFolder + "\\" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + ".dmp";
HANDLE hDumpFile = CreateFile((LPCWSTR)strPath.utf16(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDumpFile != INVALID_HANDLE_VALUE)
{
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// 写入Dump文件内容
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
return EXCEPTION_EXECUTE_HANDLER;
}
main()调用方法:
// 注冊异常捕获函数
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);