views:

249

answers:

2
+1  Q: 

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

+1  A: 

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.

JaredPar
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
@asveikau, completely agree. That's why I recomended the signal or 2 pipes. A single pipe is essentially a guaranteed race condition
JaredPar
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
A: 

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.

asveikau