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

泄露秘密 提交于 2020-01-25 03:45:09

问题


I'm working on Windows, and I'm trying to learn pipes, and how they work.

One thing I haven't found is how can I tell if there is new data on a pipe (from the child/receiver end of the pipe?

The usual method is to have a thread which reads the data, and sends it to be processed:

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

The problem is that the ReadFile() function waits for data, and then it reads it. Is there a method of telling if there is new data, without actually waiting for new data, like this:

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

回答1:


Use 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 ...
}



回答2:


One more way is to use IPC synchronization primitives such as events (CreateEvent()). In case of interprocess communication with complex logic -- you should put your attention at them too.



来源:https://stackoverflow.com/questions/11396870/how-can-i-tell-if-there-is-new-data-on-a-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!