Search code examples
c++windowswinapiprocesswin32-process

Detecting a process crash in C++/Win32


I'm working on a software that contains 2 programs : the Qt Main exe + an OpenGL Game exe

We use always the Qt Main exe at the first. When we click on the button "start game", we execute the OpenGL Game exe. No probleme to do that.

The problem is that sometime we have a crash in the OpenGL Game exe and we want to send a crash report containing the log to our compagny crash-report mail.

I found a function (registerwaitforsingleobject) in Win32 API but I don't know if the process has crashed or not : https://learn.microsoft.com/en-gb/windows/desktop/api/winbase/nf-winbase-registerwaitforsingleobject

I would like to use only the win32 api (WinXP-WinVist to Win10)

Thanks in advance


Solution

  • I found the solution to my problem : I used GetExitCodeProcess function from the Win32 API (https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess).

    This is the example code :

    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 source code :

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