views:

79

answers:

2
      fSuccess = ReadFile( 
         hPipe,    // pipe handle 
         chBuf,    // buffer to receive reply 
         BUFSIZE*sizeof(TCHAR),  // size of buffer 
         &cbRead,  // number of bytes read 
         NULL);    // not overlapped 

If not safe, how can I ensure the other side is not writing when reading a pipe in windows?

+3  A: 

Yes, this is a perfectly legal operation on the pipe. One end of the pipe can read from and write to a pipe irrespective of what is happening to the other end.

JaredPar
What if the other side has already quit when you are writing to the pipe?
Alan
@Alan then you will receive an error code.
JaredPar
What if the other side is too slow reading from the pipe, and the buffer is full when you are writing to the pipe?
wamp
A: 

It's perfectly safe -- pipes handle all the necessary synchronization on the buffers and such automatically. If you try to write to/read from a pipe when the other process has closed its connection to the pipe (either explicitly by closing the pipe, or implicitly by exiting the process) you'll get ERROR_BROKEN_PIPE from GetLastError. If you're using anonymous pipes the parent process will typically look for this to detect when the child process exited, so there will be no more data to process.

Jerry Coffin
What if the other side is too slow reading from the pipe, and the buffer is full when you are writing to the pipe?
wamp
@wamp: if memory serves, the kernel will expand the buffer -- up to a point. If the buffer is full and it's already at maximum size, I think the attempted write just blocks, though I don't remember for certain.
Jerry Coffin