Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a CLOSE_WAIT socket connection

Tags:

linux

sockets

I have written a small program that interacts with a server on a specific port. The program works fine, but:

Once the program terminated unexpectedly, and ever since that socket connection is shown in CLOSE_WAIT state. If I try to run a program it hangs and I have to force it close, which accumulates even more CLOSE_WAIT socket connections.

Is there a way to flush these connections?

like image 703
Dilletante Avatar asked Apr 09 '13 13:04

Dilletante


People also ask

What does Close_wait mean in netstat?

The CLOSE_WAIT state indicates that the remote end of the connection has finished transmitting data and that the remote application has issued a close(2) or shutdown(2) call. The local TCP stack is now waiting for the local application that owns the socket to close(2) the local socket as well.

Why there are many Close_wait sockets seen in netstat command output?

In other words it means that the local end of the connection has received 'FIN' from the other end, but the OS is waiting for the program at the local end to actually close its connection. The problem is that a program running on the local machine is not closing the socket. It is not a TCP tuning issue.

What causes Close_wait?

CLOSE_WAIT - Indicates that the server has received the first FIN signal from the client and the connection is in the process of being closed. This means the socket is waiting for the application to execute close() . A socket can be in CLOSE_WAIT state indefinitely until the application closes it.


2 Answers

CLOSE_WAIT means your program is still running, and hasn't closed the socket (and the kernel is waiting for it to do so). Add -p to netstat to get the pid, and then kill it more forcefully (with SIGKILL if needed). That should get rid of your CLOSE_WAIT sockets. You can also use ps to find the pid.

SO_REUSEADDR is for servers and TIME_WAIT sockets, so doesn't apply here.

like image 130
derobert Avatar answered Sep 28 '22 04:09

derobert


As described by Crist Clark.

CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.

The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.

Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).

like image 30
user2618402 Avatar answered Sep 28 '22 03:09

user2618402