WinAPI C++ client detect write on anonymous pipe before reading

前端 未结 3 1921
清酒与你
清酒与你 2021-01-20 23:35

I am writing a C++ (Windows) client console application which reads from an anonymous pipe on STDIN. I would like to be able to use my program as follows:

echo i         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 00:17

    Look at PeekNamedPipe(). Despite its name, it works for both named and anonymous pipes.

    int main(int argc, const char *argv[])
    {
        char char_buffer[BUFSIZE]; 
        DWORD bytes_read;
        DWORD bytes_avail;
        DWORD dw;
        HANDLE stdin_handle;
        bool is_pipe;
    
        stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
        is_pipe = !GetConsoleMode(stdin_handle, &dw);
    
        if (stdin_handle == INVALID_HANDLE_VALUE) {
            std::cout << "Error: invalid handle value!\n\n";
        } else {
            while (1) { 
                if (is_pipe) {
                    if (PeekNamedPipe(stdin_handle, NULL, 0, NULL, &bytes_avail, NULL)) {
                        if (bytes_avail == 0) {
                            Sleep(100);
                            continue;
                        }
                    }
                }
    
                if (!ReadFile(stdin_handle, char_buffer, min(bytes_avail, BUFSIZE), &bytes_read, NULL)) {
                    break; 
                }
    
                if (bytes_read == 0) {
                    break;
                }
    
                // Output what we have read so far
                for (unsigned int i = 0; i < bytes_read; i++) {
                    std::cout << char_buffer[i];
                }
            }
        }
    
        return 0;
    }
    

提交回复
热议问题