views:

44

answers:

1

I was studying the MSDN examples of using named pipes:

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 first, will this disconnect the client as well? Can server disconnect a client from a pipe without negotiating it with the client?

+1  A: 

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
Hans Passant
"The server calls ConnectNamedPipe to wait for a client connection. No data needs to be sent." Sure. Now the client connects to the pipe but is not sending anything. The pipe is busy and another client (that would acutally send some data) cannot connect to it. How can I drop the "muted" client in order to create a new pipe for other client connection?
AOI Karasu
The server can call ConnectNamedPipe again, right after it detects a connection, to allow other clients to connect. Be sure to omit FILE_FLAG_FIRST_PIPE_INSTANCE from CreateNamedPipe.
Hans Passant