简介本文向大家介绍一个C++实战项目:C++程序崩溃生成Dump文件。在程序运行时候崩溃是头疼的时,本实战项目可在程序运行崩溃时在程序目录下生成Dump文件,具有一定的C++实战价值,感兴趣的朋友可以参考一下。

Dump调试文件

C++语言中调用window API函数CreateFile()和MiniDumpWriteDump(),记录程序崩溃时的Dump信息,并保持dump文件,根据dump文件对应的源码工程和.pdb文件,快速的定位到程序崩溃的源码位置。

示例效果

C++,程序崩溃,Dump文件

点击崩溃,在程序目录下会生成Dump文件:

C++,程序崩溃,Dump文件

示例代码

// 产生DUMP文件
int GenerateMiniDump(HANDLE hFile, PEXCEPTION_POINTERS pExceptionPointers, LPCTSTR sAppName)
{
	BOOL bOwnDumpFile = FALSE;
	HANDLE hDumpFile = hFile;
	MINIDUMP_EXCEPTION_INFORMATION ExpParam;

	typedef BOOL(WINAPI * MiniDumpWriteDumpT)(
		HANDLE,
		DWORD,
		HANDLE,
		MINIDUMP_TYPE,
		PMINIDUMP_EXCEPTION_INFORMATION,
		PMINIDUMP_USER_STREAM_INFORMATION,
		PMINIDUMP_CALLBACK_INFORMATION
		);

	MiniDumpWriteDumpT pfnMiniDumpWriteDump = NULL;
	HMODULE hDbgHelp = LoadLibrary(L"DbgHelp.dll");
	if (hDbgHelp)
		pfnMiniDumpWriteDump = (MiniDumpWriteDumpT)GetProcAddress(hDbgHelp, "MiniDumpWriteDump");

	if (pfnMiniDumpWriteDump)
	{
		if (hDumpFile == NULL || hDumpFile == INVALID_HANDLE_VALUE)
		{
			TCHAR szPath[MAX_PATH] = { 0 };
			TCHAR szFileName[MAX_PATH] = { 0 };
			TCHAR dwBufferSize = MAX_PATH;
			SYSTEMTIME stLocalTime;
			GetLocalTime(&stLocalTime);

			// 得到当前模块路径
			GetModuleFileName(NULL, szPath, MAX_PATH);
			CString strModule;
			strModule = szPath;
			int iFind = strModule.ReverseFind('\\');
			strModule = strModule.Left(iFind);
			//GetTempPath(dwBufferSize, szPath);

			StringCchPrintf(szFileName, MAX_PATH, L"%s\\DumpLog", strModule);
			CreateDirectory(szFileName, NULL);

			StringCchPrintf(szFileName, MAX_PATH, L"%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
				szFileName, sAppName,
				stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
				stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
				GetCurrentProcessId(), GetCurrentThreadId());
			hDumpFile = CreateFile(szFileName, GENERIC_READ | GENERIC_WRITE,
				FILE_SHARE_WRITE | FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);

			bOwnDumpFile = TRUE;
			OutputDebugString(szFileName);
		}

		if (hDumpFile != INVALID_HANDLE_VALUE)
		{
			ExpParam.ThreadId = GetCurrentThreadId();
			ExpParam.ExceptionPointers = pExceptionPointers;
			ExpParam.ClientPointers = FALSE;

			pfnMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
				hDumpFile, MiniDumpWithDataSegs, (pExceptionPointers ? &ExpParam : NULL), NULL, NULL);

			if (bOwnDumpFile)
				CloseHandle(hDumpFile);
		}
	}

	if (hDbgHelp != NULL)
		FreeLibrary(hDbgHelp);

	return EXCEPTION_EXECUTE_HANDLER;
}

调用:

// 加入崩溃dump文件功能
SetUnhandledExceptionFilter(ExceptionFilter);

然后编写程序崩溃代码:

void CGenerateDumpTestDlg::OnBnClickedOk()
{
	int* p = NULL;
	*p = 10; // 使用了未初始化的指针p,运行崩溃
}


源码下载
  • 最近更新:   2022-06-16开发环境:   Visual Studio 2015
  • 源码大小:   133.89KB下载次数:  5 

更多为你推荐