In Linux, the close() system call on a TCP socket file descriptor is generally non-blocking. It returns immediately after initiating the socket closure, but there are nuances to consider:
Key Points:
Immediate Return:
close() does not wait for the TCP connection to fully terminate. It returns right away, even if there is data still in the socket's send buffer or if the peer hasn't acknowledged the connection closure.
TCP Connection Termination:
When close() is called, the kernel sends a FIN segment to the peer to initiate the TCP shutdown process. The actual termination of the connection (e.g., waiting for the peer's acknowledgment and final FIN/ACK exchange) is handled asynchronously by the kernel in the background.
The socket may linger in states like FIN_WAIT_1, FIN_WAIT_2, or TIME_WAIT, but these do not block the close() call itself.
Data in Send Buffer:
If there is unsent data in the socket's send buffer, the kernel will continue attempting to transmit it after close() returns. However, close() does not wait for this data to be acknowledged. The application has no guarantee that the data was fully delivered unless it explicitly uses shutdown() or other mechanisms to wait for acknowledgments.
Non-Blocking Behavior:
Even if the socket is in non-blocking mode, close() will still return immediately. The non-blocking mode affects operations like read() or write(), not close().
Edge Cases:
If another thread/process is blocked on read() or write() on the same socket, close() will unblock those operations with an error (e.g., EPIPE or EBADF), but close() itself remains non-blocking.
If the socket is in a TIME_WAIT state (due to a prior close()), subsequent close() calls on the same socket will not block.
When Might It "Seem" Blocking?
If your application expects close() to wait for all data to be sent and acknowledged, it might appear "blocking" if you rely on close() for this. However, this is not the case. To ensure data is sent, use shutdown(fd, SHUT_WR) followed by waiting for the peer's acknowledgment (e.g., via select() or poll()).
Summary:
close() on a TCP socket does not block. It returns immediately, even if the connection is not fully terminated or data remains in the send buffer.
To ensure data delivery or proper connection termination, use shutdown() and handle TCP states explicitly.