Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: socket close() vs shutdown()

Tags:

linux

tcp

So on linux, shutdown() can take a parameter SHUT_RD, SHUT_WR or SHUT_RDWR to shutdown only part of the communication channel. But in terms of the TCP messages sending to the peer, how does it work?

In TCP state machine, the closing works in a 4-way handshake fashion,

(1)           (2)
FIN---------->

   <----------ACK
   <----------FIN

ACK----------->

So what messages dose it send when I do a shutdown(sock, SHUT_RD) or shutdown(sock, SHUT_WR)?

like image 254
wei Avatar asked Feb 06 '13 23:02

wei


People also ask

When would you use Sockets to shut down?

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer.

What does closing a socket do?

close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.

Do we need to close socket?

In conclusion, not closing a socket may lead to several problems which are more or less important. Generally you can expect more problems with TCP than UDP. You should definitely close sockets if possible when you are done with them!

When should I close TCP socket?

A TCP socket that is connected should not be closed until the connection has been shut down.


2 Answers

  1. shutdown(sd, SHUT_WR) sends a FIN which the peer responds to with an ACK. Any further attempts to write to the socket will incur an error. However the peer can still continue to send data.

  2. shutdown(sd, SHUT_RD) sends nothing on the network: it just conditions the local API to return EOS for any subsequent reads on the socket. The behaviour when receiving data on a socket that has been shutdown for read is system-dependent: Unix will ACK it and throw it away; Linux will ACK it and buffer it, which will eventually stall the sender; Windows will issue an RST, which the sender sees as 'connection reset by peer'.

like image 98
user207421 Avatar answered Oct 21 '22 21:10

user207421


The FIN packets don't have to be symmetric. Each end sends FIN when its local writer has closed the socket.

like image 25
Andy Ross Avatar answered Oct 21 '22 22:10

Andy Ross