c++ - 检测 C++/Win32 中的进程崩溃

标签 c++ windows winapi process win32-process

我正在开发一个包含 2 个程序的软件:Qt Main exe + OpenGL Game exe

我们一开始总是使用 Qt Main exe。当我们点击“开始游戏”按钮时,我们执行OpenGL Game exe。这样做没问题。

问题是,有时我们的 OpenGL Game exe 发生崩溃,我们希望将包含日志的崩溃报告发送到我们公司的崩溃报告邮件。

我在 Win32 API 中发现了一个函数 (registerwaitforsingleobject),但我不知道该进程是否已崩溃: https://learn.microsoft.com/en-gb/windows/desktop/api/winbase/nf-winbase-registerwaitforsingleobject

我只想使用 win32 api(WinXP-WinVist 到 Win10)

提前致谢

最佳答案

我找到了问题的解决方案:我使用了 Win32 API 中的 GetExitCodeProcess 函数 ( https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess )。

这是示例代码:

int main(int argc, char** arv)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

const char * prgm = "CrashedProcess.exe";
LPSTR prgmLpstr = const_cast<LPSTR>(prgm);

// Start the child process. 
if (!CreateProcess(NULL,   // No module name (use command line)
    prgmLpstr,        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi)           // Pointer to PROCESS_INFORMATION structure
    )
{
    printf("CreateProcess failed (%d).\n", GetLastError());
    return -1;
}

// Wait until child process exits.
auto ret = WaitForSingleObject(pi.hProcess, INFINITE);
printf("WaitForSingleObject ret = %x\n", ret);
if (ret == WAIT_OBJECT_0)
{
    printf("WaitForSingleObject ret ret == WAIT_OBJECT_0\n");
}
BOOL b = FALSE;
DWORD n = 0;
b = GetExitCodeProcess(pi.hProcess, &n);
if (n == 0xC0000005)
{
    printf("Process Crashed !!!\n");
}

// Close process and thread handles. 
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
printf("WaitForSingleObject end\n");
return 0;
}

CrashedProcess.exe源代码:

int main()
{
   int * ptr = nullptr;
   *ptr = 123;
   return 0;
}

关于c++ - 检测 C++/Win32 中的进程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51658214/

相关文章:

c - 如何在win32应用程序中使用对话框?

c# - 读取 DTD 或 Schema 并列出给定元素的所有有效子元素或属性

windows - 如何防止使用 LsaRetrievePrivateData 从远程机器的任何人轻松读取使用 LsaStorePrivateData 存储的数据?

c++ - 将 (const) char * 转换为 LPCWSTR

windows - Emacs 创建缓冲区非常慢

c# - 在 Windows 应用程序中以编程方式选择 TreeView 中的节点

windows - 检查正在运行的进程正在调用哪个windows api

c++ - 颜色选择器,按颜色选择发送事件

c++ - 如何使 "make"成为命令?

c++ - 如何通过索引从可变模板参数包中提取值?