Search code examples
csocketsshutdown

Any cases Where close() is preferred to shutdown()?


I am a developer on an open source project and I have been having some problems with the server thinking it has answered a socket completely (meaning it has either sent a reply or closed it's end in response to a failure) and the client being stuck in poll(). After some research, I found that close() doesn't always generate a POLLHUP event, but shutdown(sock, 2) does.

In light of that, I'm considering adding a shutdown(sock,2) in the event of error handling (in addition to the close() call). Does anyone know of some reasons that this would cause problems? Am I barking up the wrong tree? I'm thinking that if the server believes that the socket is closed, the client should definitely not attempt anything else with that socket, and I can't think of a reason not to add this, but I haven't been working with tcp connections for that long and would love some advice.


Solution

  • You need to figure out why closeing the socket isn't causing it to shutdown. The most likely reason is that there is another descriptor that accesses the same endpoint. Only closeing the last endpoint causes an implicit shutdown.

    Do you ever dup the file descriptor? Do you make sure it is closed in all child processes? If the socket was in a parent process before it forked this process, did the parent close their copy?