With Windows named pipes, what is the proper way to use the CreateNamedPipe
, ConnectNamedPipe
, DisconnectNamedPipe
, and CloseHandle
calls?
I am making a server app which is connecting to a client app which connects and disconnects to the pipe multiple times across a session.
When my writes fail because the client disconnected, should I call DisconnectNamedPipe
, CloseHandle
, or nothing on my handle.
Then, to accept a new connection, should I call CreateNamedPipe
and then ConnectNamedPipe
, or just ConnectNamedPipe
?
I would very much like an explanation of the different states my pipe can be in as a result of these calls, because I have not found this elsewhere.
Additional info:
Language: Python using the win32pipe
,win32file
and win32api
libraries.
Pipe settings: WAIT, no overlap, bytestream.
Best Answer
It is good practice to call
DisconnectNamedPipe
thenCloseHandle
, althoughCloseHandle
should clean everything up.The MSDN documentation is a little vague and their server example is pretty basic. As to whether you reuse pipe handles, it seems that it is your own choice. Documentation for
DisconnectNamedPipe
seems to indicate that you can re-use a pipe handle for a new client by callingConnectNamedPipe
again on that handle after disconnecting. The role ofConnectNamedPipe
seems to be to assign a connecting client to a handle.Make sure you are cleaning up pipes though as MSDN states the following
I'd also bare the above in mind if you are creating/destroying a lot of pipes. My guess that it would be better to operate a pool of pipe handles if there are many clients and have some grow/shrink mechanism to the pool.