windows下客戶軟體崩潰異常捕捉和處理
windows下可以通過windows的API鉤子來處理崩潰異常
主要使用
WINBASEAPI
LPTOP_LEVEL_EXCEPTION_FILTER
WINAPI
SetUnhandledExceptionFilter(
__in_opt LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter
);
來處理異常
#include "stdafx.h"
#include <windows.h>
#include <DbgHelp.h>
#pragma comment(lib, "dbghelp.lib")
//我們的回撥函式
LONG __stdcall ExceptCallBack( EXCEPTION_POINTERS *pExcPointer)
{
MessageBox(NULL,"程式崩潰!相關資訊記錄在C:\\Test.dmp檔案中。",NULL,MB_OK);
//建立dump檔案
HANDLE hFile = CreateFile("C:\\Test.dmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL ,NULL);
//向檔案寫下當前程式崩潰相關資訊
MINIDUMP_EXCEPTION_INFORMATION loExceptionInfo;
loExceptionInfo.ExceptionPointers = pExcPointer;
loExceptionInfo.ThreadId = GetCurrentThreadId();
loExceptionInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),hFile, MiniDumpNormal, &loExceptionInfo, NULL, NULL);
CloseHandle(hFile);
return EXCEPTION_EXECUTE_HANDLER;
}
void WrongFun()
{
//crash
int * p = NULL;
*p = 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
//設定崩潰回撥函式
SetUnhandledExceptionFilter(ExceptCallBack);
WrongFun();
return 0;
}