调用WaitForSingleObject与CreateProcess结合使用时不明确

时间:2016-11-08 14:47:56

标签: c++ windows createprocess waitforsingleobject

我在一个跟踪进程的程序中遇到了以下代码:

void StartProcess(const std::wstring& processName, const CString& argument)
{       
    ...
    STARTUPINFO         stInfo; 
    PROCESS_INFORMATION prInfo;
    ZeroMemory( &stInfo, sizeof(stInfo) ); 
    stInfo.cb = sizeof(stInfo);
    stInfo.dwFlags=STARTF_USESHOWWINDOW;
    stInfo.wShowWindow=SW_SHOWDEFAULT;

    bRet = CreateProcess(NULL, 
        (LPTSTR)(LPCTSTR)sCmdline, 
        NULL,
        NULL, 
        TRUE,
        CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS,
        NULL,
        _T("."),                         
        &stInfo, 
        &prInfo);

    // Create process has gone OK and we have to wait.
    if (bRet)
    {   
        bRet = FALSE;
        int nRetWait = WaitForSingleObject(prInfo.hProcess,0);

        if (nRetWait == WAIT_OBJECT_0)
        {
            // Get the exit code of the process
            DWORD dwExitCode = 0;
            ::GetExitCodeProcess(prInfo.hProcess, &dwExitCode);
            if (0 == dwExitCode)
            {
                // The program succeeded                    
                m_StartedServices.push_back(prInfo.dwProcessId;);
                bRet = TRUE;
            }                
        }
    }
}

代码应该启动一个进程,然后在稍后的体育场中终止它(使用m_StartedServices)。但是我想知道WaitForSingleObjectGetExitCodeProcess的调用有什么附加价值。我看了一下,似乎超时为0的WaitForSingleObject用于检查进程是否仍在运行,但它刚刚创建,那么为什么要检查?为什么要检查仍在运行的进程的退出代码?

有人可以清楚说明吗?

我也发现了电话:

CloseHandle(prInfo.hThread);
CloseHandle(prInfo.hProcess);
此功能中缺少

。我是否发现了手柄泄漏,或者是否有一些会自动关闭手柄的魔法?

0 个答案:

没有答案
相关问题