Tibi
Tibi

Reputation: 3875

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

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

Upvotes: 1

Views: 4991

Answers (2)

westwood
westwood

Reputation: 1774

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.

Upvotes: 1

hmjd
hmjd

Reputation: 122001

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

Upvotes: 5

Related Questions