[英]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.