CreateProcess with CREATE_NEW_CONSOLE & keep the console window open

时间:2015-07-31 20:56:20

标签: c++ windows createprocess

I have a working command-line application that uses the Windows API to create a child process in a new console window. I am using the CREATE_NEW_CONSOLE flag but I need a way to keep that newly opened window from closing when the new process exits.

Here's the existing code:

STARTUPINFO si;
LPCTSTR lpAppName = "\\\\fs\\storage\\QA\\Mason\\psexec\\PSExec.exe";

string lpstr = "\\\\fs\\storage\\QA\\Mason\\psexec\\PSExec.exe \\\\" + target + " /accepteula -u user -p pass -s -realtime \\\\fs\\storage\\QA\\Mason\\psexec\\RI.bat";
LPTSTR lpCmd = CA2T(lpstr.c_str());

PROCESS_INFORMATION pi; // This structure has process id
DWORD exitCode = 9999; // Process exit code

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

// Start the child process. 
if (!CreateProcess(lpAppName,   // cmd.exe for running batch scripts
    lpCmd,        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    CREATE_NEW_CONSOLE,              // New Console Window 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
    )
{
    cout << "CreateProcess failed: " << GetLastError() << endl;
    getchar();
    return -1;
}

// Wait until child process exits.
cout << "Waiting Installation processes to complete on " << target << endl;
DWORD result = WaitForSingleObject(pi.hProcess, INFINITE);

// Get Exit Code
if (!GetExitCodeProcess(pi.hProcess, &exitCode)) {
    cout << "GetErrorCodeProcess failed: " << GetLastError() << endl;
    return -1;
}

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

How can I make the new console window remain open?

1 个答案:

答案 0 :(得分:3)

在这个特殊情况下,最简单的解决方案是作弊,即

psexec -s \\target cmd /c "\\server\share\file.bat & pause"

您已经隐式启动了cmd.exe的实例,以运行批处理文件,因此这不会带来任何重大开销。

对于更通用的解决方案,您需要启动一个代理应用程序(使用CREATE_NEW_CONSOLE)来启动目标应用程序(不带 CREATE_NEW_CONSOLE),然后等待。对于奖励积分,代理应用程序将与父应用程序相同,只是使用命令行标志启动,告诉它该做什么。