windows程序崩溃的处理方法

 

发布的Windows程序如果崩溃,可用以下代码输出错误信息并生成转储文件,以找出崩溃原因。

#ifdef _WIN32
#include 
#include 
#include 
#include "errhandlingapi.h"
#include "minidumpapiset.h"
#include "strsafe.h"
#endif

//顶级异常处理函数
LONG WINAPI TopLevelExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)

{

//输出错误信息
TCHAR szText[1024] =  {TEXT('\0')};

StringCchPrintf(szText,
                sizeof(szText)/sizeof(szText[0]),
                TEXT("ExceptionAddress=%X, ExceptionCode=%X, ExceptionFlags=%X, 
                ExceptionInformation=%X, NumberParameters=%X"),
                ExceptionInfo->ExceptionRecord->ExceptionAddress,
                ExceptionInfo->ExceptionRecord->ExceptionCode,
                ExceptionInfo->ExceptionRecord->ExceptionFlags,
                ExceptionInfo->ExceptionRecord->ExceptionInformation,
                ExceptionInfo->ExceptionRecord->NumberParameters);

MessageBox(NULL, szText, TEXT("ExceptionFilter"), MB_OK);

//保存转储文件
char szFile[MAX_PATH];
sprintf(szFile, "mydmp%d.dmp", exe_version); 

 HANDLE hDmpFile = ::CreateFile(TEXT("./log/analysis.p"),
                                   GENERIC_READ|GENERIC_WRITE,
                                   FILE_SHARE_WRITE|FILE_SHARE_READ,
                                   0, CREATE_ALWAYS, 0, 0);

    MINIDUMP_EXCEPTION_INFORMATION stInfo = {0};
    stInfo.ThreadId = GetCurrentThreadId();
    stInfo.ExceptionPointers = ExceptionInfo;
    stInfo.ClientPointers = TRUE;

    MiniDumpWriteDump(GetCurrentProcess(),
                      GetCurrentProcessId(),
                      hDmpFile, MiniDumpNormal,
                      &stInfo, NULL, NULL);


return 0;
}


//将以下代码放置在程序入口处以捕获未处理异常
SetUnhandledExceptionFilter(TopLevelExceptionFilter);

 

 

你可能感兴趣的:(C++)