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

How can I tell if there is new data on a pipe?

本文关键字:新数据 数据 是否 管道 何判断 判断      更新时间:2023-10-16

我在Windows上工作,我正在努力学习管道以及它们是如何工作的。

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

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

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

问题是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();
    }
}

使用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 ...
}

还有一种方法是使用IPC同步原语,如事件(CreateEvent())。在使用复杂逻辑进行进程间通信的情况下,您也应该关注它们。

相关文章: