Windows 命名管道部分读取

Windows named pipe partial read

当我通过 ReadFile 读取管道并且它 returns 我的部分数据时,是否可能出现这种情况,导致我再次调用 ReadFile 直到达到指定的读取字节数?

PIPE_TYPE_BYTE设置在创建命名管道的一侧。

在读取端,设置PIPE_READMODE_BYTE读取部分数据的模式

在部分阅​​读模式下,可以使用PIPE_READMODE_BYTEPIPE_NOWAIT组合来避免ReadFile函数挂起。 lpNumberOfBytesRead参数可以用来检测是否有更多的数据需要读取。当没有数据可读时,如果 ReadFile 函数调用成功,lpNumberOfBytesRead 将为零。否则,通过调用 GetLastError 函数检查错误。

基于官方样本:Named Pipe Client and Multithreaded Pipe Server.

客户端阅读相关代码将更改为:

dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT;// PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
    hPipe,    // pipe handle 
    &dwMode,  // new pipe mode 
    NULL,     // don't set maximum bytes 
    NULL);    // don't set maximum time 

// ...

WCHAR rdWChar;
do
{
    // Read from the pipe. 

    fSuccess = ReadFile(
        hPipe,    // pipe handle 
        &rdWChar,  // buffer to receive reply 
        2,        // test size, read two bytes per read operation
        &cbRead,  // number of bytes read 
        NULL);    // not overlapped 

    if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
        break;

    wprintf(L"%c", rdWChar);
} while (cbRead); // repeat loop if there is more bytes