简体   繁体   中英

CreateProcess not in primary thread

I use CreateProcess() to start a other programm from my C++ code. The helppage says that it

Creates a new process and its primary thread. The new process runs in the security context of the calling process.

I would like to have it in his own thread, so the application would keep on going. Is there any simple way to do so? I am not familar with boost and Co.

My code:

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;
}

and how to call the function:

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

Transforming the comment by ElderBug in a reply

The problem in your code is the presence of an infinite wait after the CreateProcess call:

WaitForSingleObject( pi.hProcess, INFINITE );

Just comment it and the program execution will not stop.

I also did this same error and I stumbled in this SO question; the fact is that many of us get the code from the MSDN example here (without much attention), which has in fact this infinite wait.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM