Windows QT程序崩溃 生成dmp文件

1、简介
程序开发时无法避免碰到各种崩溃问题,记录下出现崩溃问题查找BUG方法,代码如下
2、提示,只测试了该方法在QT msvc编译器的效果,MinWG变一下生成的dmp文件名为乱码

// An highlighted block
#include <Windows.h>
#include <DbgHelp.h>
#include <winnt.h>
#include <time.h>
#include <locale>
#include <codecvt>
#include <tchar.h>
LONG __stdcall ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
    //程式异常捕获
    //创建 Dump 文件
    char str_time[100];
    memset(str_time, 0, 100);
    struct tm *local_time = NULL;
    time_t utc_time;
    utc_time = time(NULL);
    local_time = localtime(&utc_time);
    strftime(str_time, 100, "%Y%m%d%H%M%S", local_time);

    std::string timeStr(str_time);
    std::string dumpFilePath = timeStr + ".dmp";
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    std::wstring wide = converter.from_bytes(dumpFilePath);
    HANDLE hDumpFile = CreateFile(wide.c_str(),GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (hDumpFile != INVALID_HANDLE_VALUE) {
        //Dump信息
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pException;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = TRUE;
        //写入Dump文件内容
        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
    }
    //这里弹出一个错误对话框并退出程序
    EXCEPTION_RECORD* record = pException->ExceptionRecord;
    fprintf(stderr, "record->ExceptionCode:%lu\n", record->ExceptionCode);
    return EXCEPTION_EXECUTE_HANDLER;

}
void DisableSetUnhandledExceptionFilter()
{

    HMODULE h_hand = LoadLibrary(TEXT("kernel32.dll"));

    void *addr = (void*)GetProcAddress(h_hand,"SetUnhandledExceptionFilter");
    if (addr)
    {
        unsigned char code[16];

        int size = 0;

        code[size++] = 0x33;

        code[size++] = 0xC0;

        code[size++] = 0xC2;

        code[size++] = 0x04;

        code[size++] = 0x00;

        DWORD dwOldFlag, dwTempFlag;

        VirtualProtect(addr, size, PAGE_READWRITE, &dwOldFlag);
        printf("WriteProcessMemory start!\n");
        WriteProcessMemory(GetCurrentProcess(), addr, code, size, NULL);
        printf("WriteProcessMemory end!\n");
        VirtualProtect(addr, size, dwOldFlag, &dwTempFlag);
    }
}

void RunCrashHandlerLocal()
{
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);//注册异常捕获函数
}

int main(int argc, char *argv[])
{
    RunCrashHandlerLocal();
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值