Created
August 28, 2023 16:15
-
-
Save aneury1/5614eb927c2b6f9e3a142deae8129fd4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set up the command and process information structures | |
STARTUPINFO startupInfo = {}; | |
startupInfo.cb = sizeof(startupInfo); | |
SECURITY_ATTRIBUTES saAttr = {}; | |
saAttr.nLength = sizeof(saAttr); | |
saAttr.bInheritHandle = TRUE; | |
// Create pipes for redirecting standard output | |
HANDLE hChildStd_OUT_Rd = NULL; | |
HANDLE hChildStd_OUT_Wr = NULL; | |
if (!CreatePipe(&hChildStd_OUT_Rd, &hChildStd_OUT_Wr, &saAttr, 0)) { | |
std::cerr << "CreatePipe failed\n"; | |
return 1; | |
} | |
// Ensure the read handle to the pipe for STDOUT is not inherited | |
SetHandleInformation(hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0); | |
// Update startup information to use the write end of the pipe | |
startupInfo.hStdOutput = hChildStd_OUT_Wr; | |
startupInfo.dwFlags |= STARTF_USESTDHANDLES; | |
// Create the process | |
PROCESS_INFORMATION processInfo = {}; | |
if (!CreateProcess(batchFilePath, (LPWSTR)batchFilePath, nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startupInfo, &processInfo)) { | |
std::cerr << "CreateProcess failed\n"; | |
return 1; | |
} | |
// Close the write end of the pipe since it's not needed in this process | |
CloseHandle(hChildStd_OUT_Wr); | |
// Read and print the output from the process | |
CHAR buffer[4096*6]; | |
DWORD bytesRead; | |
int line = 1; | |
while (ReadFile(hChildStd_OUT_Rd, buffer, sizeof(buffer), &bytesRead, nullptr) && bytesRead > 0) { | |
buffer[bytesRead] = '\0'; | |
std::cout<<line<<": " << buffer; | |
memset(buffer, 0x00, sizeof(buffer)); | |
line++; | |
} | |
// Close handles | |
CloseHandle(hChildStd_OUT_Rd); | |
CloseHandle(processInfo.hProcess); | |
CloseHandle(processInfo.hThread); | |
return 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment