Win32 ReadFile hangs when reading from pipe

前端 未结 3 839
慢半拍i
慢半拍i 2021-01-05 07:10

I am creating a child process, and reading its output. My code works fine when the child process creates output (cmd /c echo Hello World), however ReadFile will

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 07:56

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

提交回复
热议问题