使用 CREATE_NEW_CONSOLE 创建进程并保持控制台 window 打开

CreateProcess with CREATE_NEW_CONSOLE & keep the console window open

我有一个可用的命令行应用程序,它使用 Windows API 在新控制台 window 中创建子进程。我正在使用 CREATE_NEW_CONSOLE 标志,但我需要一种方法来防止新打开的 window 在新进程退出时关闭。

这是现有代码:

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

如何让新控制台 window 保持打开状态?

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

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

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

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