I am using CreateProcess()
to run cmd.exe
(without the physical window showing to the user) and need to process the output. I have decided to use CreatePipe()
for this purpose.
I am currently having an issue whereby all of my output is being read and processed, but the final call to ReadFile()
is hanging. Searching around has told me that I need to close the write side of the pipe before reading, and that this is a solution to this problem, but I have already done this and still have the problem.
Here is my code:
// sw -> path to cmd.exe, ptr is the command
ok = CreateProcess(sw, ptr, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &StartupInfo, &ProcessInfo);
CloseHandle(hStdInPipeRead);
char buf[1024 + 1] = {};
DWORD dwRead = 0;
DWORD dwAvailable = 0;
DWORD testRes;
CloseHandle(hStdOutPipeWrite);
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
// String handling for initial read omitted for clarity
string temp = buf;
bool holdOff = false;
while (ok == TRUE)
{
buf[dwRead] = '\0';
OutputDebugStringA(buf);
puts(buf);
// ReadFile gets all the correct output from cmd here but it also hangs on the very last call. How to fix?
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
temp = buf;
// handle and store output
break;
}
CloseHandle(hStdOutPipeRead);
CloseHandle(hStdInPipeWrite);