"Un-associate" 来自完成端口的套接字

"Un-associate" socket from completion port

CreateIoCompletionPort() 用于将套接字与完成端口相关联。但是,当这个套接字关闭时,我需要从完成端口 "un-associate" 它。我该怎么做?

与 I/O 完成端口关联的句柄在句柄关闭时从端口中删除。在网络套接字的情况下,通过调用 closesocket().

关闭句柄

CreateIoCompletionPort 的文档包含有关资源处理的注释:

The handle passed in the FileHandle parameter can be any handle that supports overlapped I/O. Most commonly, this is a handle opened by the CreateFile function using the FILE_FLAG_OVERLAPPED flag (for example, files, mail slots, and pipes). Objects created by other functions such as socket can also be associated with an I/O completion port. For an example using sockets, see AcceptEx. A handle can be associated with only one I/O completion port, and after the association is made, the handle remains associated with that I/O completion port until it is closed.

...

The I/O completion port handle and every file handle associated with that particular I/O completion port are known as references to the I/O completion port. The I/O completion port is released when there are no more references to it. Therefore, all of these handles must be properly closed to release the I/O completion port and its associated system resources. After these conditions are satisfied, close the I/O completion port handle by calling the CloseHandle function.

Microsoft 显然不希望普通用户这样做,但尽管如此,还是有一个官方记录的方法(而且只需要疯狂地挖掘就可以找到它):

呼叫 NtSetInformationFile, passing the value FileReplaceCompletionInformation for the FileInformationClass parameter, will get it done. (This value is defined in FILE_INFORMATION_CLASS)

此参数值的描述副本(强调我的):

Change or remove the I/O completion port for the specified file handle. The caller supplies a pointer to a FILE_COMPLETION_INFORMATION structure that specifies a port handle and a completion key. If the port handle is non-NULL, this handle specifies a new I/O completion port to associate with the file handle. To remove the I/O completion port associated with the file handle, set the port handle in the structure to NULL. To get a port handle, a user-mode caller can call the CreateIoCompletionPort function.