Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of shutdown(sock, SHUT_RD) with TCP

When using a TCP socket, what does

shutdown(sock, SHUT_RD);

actually do? Does it just make all recv() calls return an error code? If so, which error code?

Does it cause any packets to be sent by the underlying TCP connection? What happens to any data that the other side sends at this point - is it kept, and the window size of the connection keeps shrinking until it gets to 0, or is it just discarded, and the window size doesn't shrink?

like image 348
Claudiu Avatar asked Apr 11 '09 21:04

Claudiu


People also ask

What does socket shutdown do?

When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed.

Why should an application call shutdown with an argument of Shut_rdwr instead of just calling close?

shutdown is a flexible way to block communication in one or both directions. When the second parameter is SHUT_RDWR , it will block both sending and receiving (like close ). However, close is the way to actually destroy a socket.

How TCP is work for socket?

The TCP protocol is a byte stream service. It does not know anything about the format of the data being sent. It simply takes the data, encapsulates it into a TCP packet, and sends it to the remote peer. The TCP socket then keeps sent packets in memory and waits for an acknowledge from the remote peer.

What is the difference between closing a socket and using shutdown?

Generally the difference between close() and shutdown() is: close() closes the socket id for the process but the connection is still opened if another process shares this socket id. The connection stays opened both for read and write, and sometimes this is very important.


1 Answers

Shutting down the read side of a socket will cause any blocked recv (or similar) calls to return 0 (indicating graceful shutdown). I don't know what will happen to data currently traveling up the IP stack. It will most certainly ignore data that is in-flight from the other side. It will not affect writes to that socket at all.

In fact, judicious use of shutdown is a good way to ensure that you clean up as soon as you're done. An HTTP client that doesn't use keepalive can shutdown the write-side as soon as it is done sending the request, and a server that sees Connection: closed can likewise shutdown the read-side as soon as it is done receiving the request. This will cause any further erroneous activity to be immediately obvious, which is very useful when writing protocol-level code.

like image 159
Tom Avatar answered Oct 31 '22 18:10

Tom