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

4

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

以下是现有的代码:

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

我该如何让新的控制台窗口保持打开状态?


在命令的末尾添加“& pause”。 - kirbyfan64sos
父进程是什么类型的进程(命令行或GUI)?也就是说,您是否已经拥有自己的控制台窗口? - Harry Johnston
@kirbyfan64sos 不行,那个方法不起作用。我猜是因为我没有启动 cmd.exe?我只是使用它的命令来启动 psexec.exe。 - MGItkin
@HarryJohnston 这是一个命令行进程,用于启动另一个命令行进程。是的,它已经有了自己的窗口! - MGItkin
1个回答

4
在这种情况下,最简单的解决方案是作弊,即:
psexec -s \\target cmd /c "\\server\share\file.bat & pause"

您已经在隐式地启动一个 cmd.exe 实例来运行批处理文件,因此这不会引入任何显著的开销。

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


作弊解决方案似乎有效,但仅当我的.bat文件路径为非UNC时才有效。如果路径是UNC路径,则某些字符串会出错,并发送错误的命令到psexec.exe。另一个解决方案看起来更好,但我不会实施它,因为我已经决定让窗口关闭。感谢您的帮助! - MGItkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接