简体   繁体   中英

ReadFile hanging on pipe reading

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);

The child process will inherit the handle of pipe if you set SECURITY_ATTRIBUTES.bInheritHandle = true , the write handle of the pipe you closed is only the parent's, there is still a handle in child process(stdout of child), and it hasn't been closed in cihld process, Readfile fails and returns only when all write handles are closed or errors occur.

In addition, Anonymous Pipe Operations .

Asynchronous (overlapped) read and write operations are not supported by anonymous pipes(Create by CreatePipe ).

So, If you still need to send command to child process to execute cmd, you should put ReadFile in a thread. And if you don't need any more, terminate child process:

TerminateProcess(ProcessInfo.hProcess,0);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM