Home > Enterprise >  Purpose of SHUT_RDWR in shutdown() function in socket programming
Purpose of SHUT_RDWR in shutdown() function in socket programming

Time:03-21

When we call the shutdown() function on a socket with argument SHUT_RDWR, we stop read/write possibility on the socket, but the socket is still not destroyed. I can't understand the purpose of SHUT_RDWR. What does it give to us, and why do we need a socket without read/write possibility? I expect SHUT_RDWR should work as the close() function, but it is not.

CodePudding user response:

What SHUT_RDWR does is it closes the connection on the socket while keeping the handle for the data (the file descriptor) open.

For example, suppose a socket has been used for two-way communication and your end of the connection shuts it down with SHUT_RDWR. Then if the person on the other end of the connection tries to write (and perhaps read as well?), it will fail because the connection has been closed.

However, the file descriptor is still open, which means that if there is any data left for you to receive/read, you can go ahead and do it, and then close the file descriptor.

In other words, shutdown() is about closing off the connection, and close() is about closing the file descriptor and discarding any data that may be in the file description's "buffer."

Advanced Programming in the UNIX Environment also has this reason:

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.

  • Related