I was studying the MSDN examples of using named pipes:
- Named pipe server using overlapped I/O
- Named pipe client
The server easily detects when the client is disconnected and creates a instance of a named pipe. But I cannot figure out how the server knows that a client is connected to a pipe before any data from client is sent.
Can server detect a connceted client before client sends any data?
If server calls DisconnectNamedPipe
before client disconnects itself fir开发者_开发百科st, will this disconnect the client as well? Can server disconnect a client from a pipe without negotiating it with the client?
Not sure I understand the hang-up. The server calls ConnectNamedPipe to wait for a client connection. No data needs to be sent. Nor can it be sent, you cannot issue a ReadFile until a client is connected. Note that the SDK sample uses this as well.
If the server disconnects ungracefully (without notifying the client with some kind of message so it can close its end of the pipe) then the client will get an error, ERROR_PIPE_NOTCONNECTED (I think). There's little reason to rely on that for a normal shutdown, you need to do something reasonable when the pipe server process crashed and burned unexpectedly.
Beware that pipes are tricky to get right due to their asynchronous nature. Getting errors that are not actually problems is common and you'll need to deal with it. My pipe code deals with these errors:
- ConnectNamedPipe: ERROR_PIPE_CONNECTED on connection race, ignore
- FlushFileBuffers: race on pipe closure, ignore all errors
- WaitNamedPipe: ERROR_FILE_NOT_FOUND if the timeout expired, translate to WAIT_TIMEOUT
- CreateFile: ERROR_PIPE_BUSY if another client managed to grab the pipe first, repeat
Server works incorrectly when clients get ERROR_FILE_NOT_FOUND
error during WaitNamedPipe()
or/and CreateFile()
calls. This error code means there no pipes with specified name available on server. You should create new pipe on server immediately after ConnectNamedPipe()
call to avoid this issue.
精彩评论