问题
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