带有参数死锁的C ++ CreateProcess

时间:2017-07-20 10:56:49

标签: c++ deadlock createprocess

我有两个应用程序(exe)。

第一个(client.exe)只打印出参数:

#include <iostream>

int main(int argc, char** argv) 
{
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) 
    {
        std::cout << argv[i] << std::endl;
    }

    return 0;
}

第二个(SandBox.exe)用一些参数执行第一个:

#include <iostream>
#include <Windows.h>

void startup(LPCTSTR lpApplicationName, LPSTR param)
{
    // additional information
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    // set the size of the structures
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // start the program up
    CreateProcess(lpApplicationName,   // the path
        param,//NULL,//argv[1],        // 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
    );

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

int main()
{
    startup(TEXT("client.exe"), TEXT("client.exe thisIsMyFirstParaMeter AndTheSecond"));
    return 0;
}

通过执行client.exe中的SandBox.exe,输出非常奇怪, client.exe永远不会结束并保持死锁

enter image description here

这里有什么问题?

我期待一些输出(比如当我运行client.exe隔离时):

enter image description here

谢谢

1 个答案:

答案 0 :(得分:3)

您的控制应用程序应该等到客户端退出。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx

// start the program up
CreateProcess(lpApplicationName,   // the path
    param,          // 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
);

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

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