I am wondering if there is a way to detect the status of client pipe's handle from the server side on Windows platform.
Even though the client closed the pipe(disconnected) with
CloseHandle() function, there seems to be no way to detect it from the server side.
WaitForSingleObject() with handle object returns
WAIT_OBJECT_0, regardless of the status of client handle. So, what would be a good solution to detect whether client pipe's handle is closed or not from server side with less cost?
If you are reading data from the pipe (
PIPE_ACCESS_DUPLEX) you will get
ERROR_BROKEN_PIPE when the client closes their end of the pipe. Even if you aren't ready to process data from the pipe you could start reading it ahead of time (using asynchronous I/O) in order to detect when the pipe is broken.
Note that if there is more than one handle to the client end of the pipe, it will only be considered closed when the last handle to it is closed. This might be an issue, for example, if the client inadvertently causes a subprocess to inherit a copy of the handle.
I don't know of any way to detect that the client has closed an outbound-only pipe without writing data to it. The best option may be to use
PIPE_ACCESS_DUPLEX even if the incoming side of the pipe is only ever used to detect when the pipe has been broken.
For future reference, although a handle can be used as a synchronization object, doing so is not recommended and as far as I know the only supported use is to detect the completion of an asynchronous I/O operation where no event object was specified.