簡體   English   中英

CreateProcess 不在主線程中

[英]CreateProcess not in primary thread

我使用 CreateProcess() 從我的 C++ 代碼啟動另一個程序。 helppage說它

創建一個新進程及其主線程。 新進程在調用進程的安全上下文中運行。

我想在他自己的線程中使用它,以便應用程序繼續運行。 有什么簡單的方法可以做到嗎? 我對 boost 和 Co 不熟悉。

我的代碼:

bool startup(LPWSTR lpApplicationName)
{
   STARTUPINFO si;
    PROCESS_INFORMATION pi;

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

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        lpApplicationName,        // 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 false;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    return true;
}

以及如何調用該函數:

int _tmain(int argc, _TCHAR* argv[])
{
wchar_t path[] = L"C:\\path\\to\\paridise.exe";
startup(path);
}

在回復中轉換 ElderBug 的評論

您的代碼中的問題是在CreateProcess調用后存在無限等待:

WaitForSingleObject(pi.hProcess, INFINITE);

只需注釋它,程序執行就不會停止。

我也犯了同樣的錯誤,我偶然發現了這個問題; 事實是,我們中的許多人從這里的 MSDN 示例中獲取代碼(沒有太多注意),實際上這是無限等待。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM