当我们调用shutdown()
时带有参数 SHUT_RDWR
的套接字上的函数,我们停止了套接字上的读/写可能性,但套接字仍然没有被破坏。我无法理解 SHUT_RDWR
的目的。它给我们带来了什么,为什么我们需要一个没有读/写可能性的套接字?我预计SHUT_RDWR
应该像close()
一样工作功能,但事实并非如此。
最佳答案
什么SHUT_RDWR
它的作用是关闭套接字上的连接,同时保持数据句柄(文件描述符)打开。
例如,假设一个套接字已用于双向通信,并且连接端使用 SHUT_RDWR
将其关闭。 。然后,如果连接另一端的人尝试写入(也许也读取?),它将失败,因为连接已关闭。
但是,文件描述符仍然处于打开状态,这意味着如果还有任何数据可供您接收/读取,您可以继续执行,然后关闭文件描述符。
换句话说,shutdown() 是关于关闭连接,而 close() 是关于关闭文件描述符并丢弃文件描述“缓冲区”中可能存在的任何数据。
UNIX环境下的高级编程也有这个原因:
Given that we can close a socket, why is shutdown needed? There are several reasons. First, close will deallocate the network endpoint only when the last active reference is closed. If we duplicate the socket (with dup, for example), the socket won’t be deallocated until we close the last file descriptor referring to it. The shutdown function allows us to deactivate a socket independently of the number of active file descriptors referencing it.
关于c - 套接字编程中shutdown()函数中SHUT_RDWR的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71546662/