Why are connections in FIN_WAIT2 state not closed by the Linux kernel?
Solution 1:
The kernel timeout only applies if the connection is orphaned. If the connection is still attached to a socket, the program that owns that socket is responsible for timing out the shutdown of the connection. Likely it has called shutdown
and is waiting for the connection to shut down cleanly. The application can wait as long as it likes for the shutdown to complete.
The typical clean shutdown flow goes like this:
The application decides to shut down the connection and shuts down the write side of the connection.
The application waits for the other side to shut down its half of the connection.
The application detects the other side's shutdown of the connection and closes its socket.
The application can wait at step 2 for as long as it likes.
It sounds like the application needs a timeout. Once it decides to shut the connection down, it should give up waiting for the other side to do a clean shutdown after some reasonable amount of time.
Solution 2:
If the socket is shutdown(), but not close() yet, the socket will stay in FIN_WAIT2 state. And since the application still owns the file descriptor, the kernel wouldn't bother to clean up.