Win32 ReadFile hangs when reading from pipe

痞子三分冷 提交于 2019-11-30 20:24:55

You redirect the output of the process to a pipe, start the process, wait till it exits, and then read the output.

The problem is that windows buffers just a limited amount of data. So you must read the pipe while the process is still running, otherwise the process will be blocked because it cannot write any more data to the pipe.

You should close the write end of the output pipe before you read from it, as @Marcus suggested in the comment.

CloseHandle(g_hChildStd_OUT_Wr);

For me this is the real answer.

You could use PeekNamedPipe in a loop like this:

for (;;)
{
    DWORD bytesAvail = 0;
    if (!PeekNamedPipe(stdoutPipeRead, NULL, 0, NULL, &bytesAvail, NULL)) {
        std::cout << "Failed to call PeekNamedPipe" << std::endl;
    }
    if (bytesAvail) {
        CHAR buf[BUFSIZE];
        DWORD n;
        BOOL success = ReadFile(stdoutPipeRead, buf, BUFSIZE, &n, NULL);
        if (!success || n == 0) {
            std::cout << "Failed to call ReadFile" << std::endl;
        }
        std::cout << std::string(buf, buf + n);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!