【问题标题】:CreateProcess with CREATE_NEW_CONSOLE & keep the console window openCreateProcess 与 CREATE_NEW_CONSOLE 并保持控制台窗口打开
【发布时间】:2023-03-05 06:28:01
【问题描述】:

我有一个可用的命令行应用程序,它使用 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);

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

【问题讨论】:

  • 在命令末尾添加&amp; pause。
  • 父进程是什么类型的进程(命令行或 GUI)?也就是说,您是否已经拥有自己的控制台窗口?
  • @kirbyfan64sos 不,那没用。我猜是因为我没有启动 cmd.exe ??我只是用它的命令启动 psexec.exe
  • @HarryJohnston 它是一个命令行进程来启动另一个命令行进程。是的,它已经有了自己的窗口!

标签: c++ windows createprocess


【解决方案1】:

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

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

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

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

【讨论】:

  • 作弊解决方案似乎有效,但前提是我的 .bat 文件的路径是 NON-UNC 如果路径是 UNC 路径,则字符串会被弄乱并且错误的命令被发送到 psexec 。可执行程序。另一个解决方案看起来是一个更好的主意,但我不会实施它,因为我决定让窗口关闭。感谢您的帮助!
猜你喜欢
  • 2014-04-20
  • 2010-12-26
  • 2013-06-01
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多