繁体   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