如何判断管道上是否有新数据?

Tib*_*ibi 1 c++ winapi pipe named-pipes

我正在 Windows 上工作,我正在尝试学习管道及其工作原理。

我还没有发现的一件事是如何判断管道上是否有新数据(来自管道的子/接收器端?

通常的方法是有一个线程读取数据并将其发送以进行处理:

void GetDataThread()
{
    while(notDone)
    {
        BOOL result = ReadFile (pipe_handle, buffer, buffer_size, &bytes_read, NULL);
        if (result) DoSomethingWithTheData(buffer, bytes_read);
        else Fail();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是 ReadFile() 函数等待数据,然后读取数据。有没有一种方法可以判断是否有新数据,而无需实际等待新数据,如下所示:

void GetDataThread()
{
    while(notDone)
    {
        BOOL result = IsThereNewData (pipe_handle);
        if (result) {
             result = ReadFile (pipe_handle, buffer, buffer_size, &bytes_read, NULL);
             if (result) DoSomethingWithTheData(buffer, bytes_read);
             else Fail();
        }

        DoSomethingInterestingInsteadOfHangingTheThreadSinceWeHaveLimitedNumberOfThreads();
    }
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 5

使用PeekNamedPipe()

DWORD total_available_bytes;
if (FALSE == PeekNamedPipe(pipe_handle,
                           0,
                           0,
                           0,
                           &total_available_bytes,
                           0))
{
    // Handle failure.
}
else if (total_available_bytes > 0)
{
    // Read data from pipe ...
}
Run Code Online (Sandbox Code Playgroud)