A great low-level networking question!
In Linux, the answer is: yes, close() can block on a TCP socket file descriptor (FD) under certain circumstances.
Here's what's going on:
When you call close() on a TCP socket FD, the kernel initiates the TCP connection termination sequence, which involves sending a FIN packet to the peer and waiting for the peer's FIN or ACK response (depending on the socket's state). This is known as the TCP shutdown or connection termination process (see RFC 793, Section 3.5).
Now, by default, close() on a TCP socket will:
- Disable further sends and receives on the socket (i.e., mark the socket as "dead").
- Initiate the TCP shutdown sequence (send
FIN packet).
- Wait for the TCP shutdown sequence to complete (i.e., wait for the peer's response).
Here's the important part: step 3 can block.
If the peer is:
- Responsive: The TCP shutdown completes quickly (usually in a few milliseconds), and
close() returns immediately.
- Unresponsive (e.g., peer crashed, network partition, or firewall blocking packets): The kernel will retransmit the
FIN packet multiple times (typically 3-5 attempts, spaced ~200-500 ms apart) waiting for an ACK or FIN response that never arrives.
During this retransmission period (which can last seconds or even minutes, depending on the network configuration and timeouts), the close() call is blocked in the kernel, waiting for:
- An
ACK or FIN response from the peer.
- The retransmission timeouts to expire.
While close() is blocked, your process is in an uninterruptible sleep state (usually denoted as D state in ps output). This means:
- Your process can't be killed or interrupted (not even by
SIGKILL).
- No signals are delivered to your process.
- The process is effectively "stuck" in the kernel.
When will this happen? Common scenarios include:
- Peer crash or reboot: The peer doesn't respond to the
FIN packet.
- Network connectivity issues: Firewall, routing problems, or congested networks cause packet loss.
- Peer socket not closed: The peer process doesn't close its socket, so no
FIN is sent back.
To avoid blocking close():
- Use
SO_LINGER with struct linger { l_onoff=1, l_linger=0 } (see man 7 socket): This sets the socket to abort the connection termination sequence when close() is called, effectively discarding any pending data and skipping the wait for peer response. Warning: Data loss may occur!
- Use
shutdown() (see man 2 shutdown) before close(): shutdown() initiates the TCP shutdown sequence, allowing you to timeout and control the disconnection process. After shutdown(), close() will not block (as the socket is already "dead").
shutdown(fd, SHUT_RDWR); // stop sends & receives, initiate TCP shutdown
// optionally, set a timeout here (e.g., using poll() or select())
close(fd); // won't block
- Use non-blocking sockets (
O_NONBLOCK or SOCK_NONBLOCK): Even with non-blocking sockets, close() may still block (briefly) if the socket is in a LINGER state (i.e., data still pending). However, the block time is usually shorter (~1-2 seconds).
Here's some example code demonstrating the blocking behavior:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int fd = socket(AF_INET, SOCK_STREAM, 0);
// connect to a server (e.g., a non-existent or firewalled host)
struct sockaddr_in srv = { .sin_family = AF_INET, .sin_port = htons(1234) };
inet_pton(AF_INET, "192.0.2.1", &srv.sin_addr); // example "unreachable" IP
connect(fd, (struct sockaddr*)&srv, sizeof(srv));
// now, close() will block waiting for TCP shutdown completion...
printf("Closing socket...\n");
close(fd); // might block for seconds/minutes...
printf("Socket closed.\n");
return 0;
}
Run this example and observe how close() blocks (use strace or ltrace to verify).
In summary:
close() on a TCP socket FD can block if the peer doesn't respond during the TCP shutdown sequence.
- Use
SO_LINGER, shutdown(), or non-blocking sockets to mitigate or avoid blocking close() calls.
Hope this exhaustive answer helped! Do you have follow-up questions?