![](/img/trans.png)
[英]CreateProcess( ) doesn't create a new window with CREATE_NEW_CONSOLE flag - C/C++
[英]CreateProcess with CREATE_NEW_CONSOLE & keep the console window open
我有一个工作的命令行应用程序,该应用程序使用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);
如何使新的控制台窗口保持打开状态?
在这种特定情况下,最简单的解决方案是作弊,即
psexec -s \\target cmd /c "\\server\share\file.bat & pause"
您已经在隐式启动cmd.exe
实例,以运行批处理文件,因此不会带来任何重大开销。
对于更通用的解决方案,您需要启动代理应用程序(使用CREATE_NEW_CONSOLE
),该代理应用程序启动目标应用程序( 不使用 CREATE_NEW_CONSOLE
),然后等待。 为了获得加分,代理应用程序将与父应用程序相同,只是使用一个命令行标志启动该应用程序,告诉它该做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.