SetUnhandledExceptionFilter : http://msdn.microsoft.com/library/defau ... filter.asp
MiniDumpWriteDump : http://msdn.microsoft.com/library/defau ... tedump.asp
在程式一開始的地方, 如 main 或是 app 的 init 的地方加上
SetUnhandledExceptionFilter ( MyCrashHandlerFunction ) ;
然後定義一個 MyCrashHandlerFunction 如下,
代碼: 選擇全部
LONG __stdcall TheCrashHandlerFunction ( EXCEPTION_POINTERS * pExPtrs )
{
TCHAR path_buffer[_MAX_PATH];
TCHAR drive[_MAX_DRIVE];
TCHAR dir[_MAX_DIR];
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, path_buffer, MAX_PATH);
_tsplitpath( path_buffer, drive, dir, fname, ext );
TCHAR DumpPath[_MAX_PATH];
TCHAR timer[50];
time_t t;
time(&t);
struct tm *ltime = localtime(&t);
_tcsftime(timer, sizeof timer, _T("%Y%m%d-%H%M%S"), ltime);
_tcscpy(DumpPath,drive);
_tcscat(DumpPath,dir);
_tcscat(DumpPath,timer);
_tcscat(DumpPath,_T("crash.dmp"));
HANDLE hMiniDumpFile = CreateFile(
DumpPath,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
NULL);
MINIDUMP_EXCEPTION_INformATION eInfo;
eInfo.ThreadId = GetCurrentThreadId();
eInfo.ExceptionPointers = pExPtrs;
eInfo.ClientPointers = TRUE;
MiniDumpWriteDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hMiniDumpFile,
MiniDumpNormal,
&eInfo,
NULL,
NULL);
//MessageBox(0, _T("sorry for crash"), _T(""), 0)
CloseHandle(hMiniDumpFile);
return EXCEPTION_EXECUTE_HANDLER;
}
便能很容易地產生 crash 的 dump file, 接下來再配合 WinDBG 的 .ecxr 指令搭配 map 及 symbol file 就能容易地找到問題的程式碼所在!
另外關於 MiniDumpWriteDump 的部分必需使用 dbghelp.lib / dbghelp.h 來編譯程式, 以及在 2000 以下 os 要搭配 dbghelp.dll 一併發行才能使用哦, 否則就只有 handle 而無法 dump 出 crash 的 dump file 了!