Search code examples
linuxsocketsfreebsdnonblocking

How to close a non-blocking socket?


I believe that if we call close system call on a non-blocking socket it returns immediately, then how to handle the response? whether it is closed or not? in other words what is the behavior of the socket system call close on a non-blocking socket?


Solution

  • if we call close system call on a non-blocking socket it returns immediately

    The socket is always closed: the connection may still be writing to the peer. But your question embodies a fallacy: if you call close() on any socket it will return immediately. Closing and writing to a socket is asynchronous. You can control that with SO_LINGER as per the other answer, although I suspect that only applies to blocking mode. Probably you should put the socket back into blocking mode before closing with a positive SO_LINGER if that's what you need to do.