Named Pipe Problem

Is there a function that returns when the other end successfully called ReadFile on the pipe. I have 2 application communicating on a named pipe, one sends a request on the pipe using WriteFile and expects an answer so it calls ReadFile. The problem is that the application is reading its own request as the answer since the other end did not remove it from the pipe yet.

Is there such a function?

I know an alternative would be to either use 2 unidirectional pipes or implement some kind or synchronization by having the other application signal the sender when it got its message but I'm just checking if there is a simpler way...

13.10.2009 22:16:06
2 ОТВЕТА

I think the method you are looking for is PeekNamedPipe. This function will allow you to look at the pipe without removing the data. You can use this to check and see if the message you just sent is still in the pipe. If so then the other end hasn't read the message yet.

Overall though, I think you're better off going with a signal or two unidirectional pipes. They are better suited for 2 way communication.

1
13.10.2009 22:25:43
I would caution against using PeekNamedPipe() here. When your program returns from PeekNamedPipe(), if two processes are reading/writing on the pipe simultaneously this becomes problematic and prone to races, as you'll never be able to rely on the value it returned still being there by the time you get to your ReadFile() call.
asveikau 13.10.2009 22:36:28
@asveikau, completely agree. That's why I recomended the signal or 2 pipes. A single pipe is essentially a guaranteed race condition
JaredPar 13.10.2009 22:39:55
Also, what's to say that the other application hasn't read the data you posted on the pipe and simply written it straight back and is now waiting for you......
ScaryAardvark 20.01.2010 08:41:15

Your design is inherently prone to race conditions and I would urge you to use two pipes instead. In particular, have you considered what happens when two processes want to write to the same pipe?

That said... You can potentially use an event to synchronize. After you're done with WriteFile(), you can wait for the event to be signalled. When the other end is done with ReadFile(), it can SetEvent(). That might work, provided the two ends have a well defined contract and don't race with each other or deadlock one another.

0
13.10.2009 22:30:34