Retrieving data from an already closed socket?

Suppose I have a server application - the connection is through TCP using UNIX sockets.

A connection is asynchronous — in other words, client and server sockets are not blocked.

Suppose that in some cases the server may decide to send some data to the connected client and immediately close the connection: using shutdown with SHUT_RDWR .

So my question is: is it guaranteed that when the recv client is called, it will receive data (sent by the server)?

Or, in order to receive data, recv must be called before the shutdown server? If so, then what should I do (or, more precisely, how to do it) to make sure that the data is received by the client?

+6
source share
3 answers

You can control this behavior with "setsockopt (SO_LINGER)":

SO_LINGER Waits for the close function to complete if data is present. When this option is turned on and unsent data appears, when a function is called, the calling application is blocked during the close function until the data is transferred or the connection time is up. The close function returns without blocking the caller. This option only makes sense for stream sockets.

See also:

+5
source

There is no guarantee that you will receive any data, not to mention this data, but data waiting for the socket to close is subject to the same guarantees as all other data: if it arrives, it will arrive in order and intact and subject to the best efforts of TCP.

NB Asynchronous and non-blocking are two different things, not two terms for the same thing.

+3
source

Once you have successfully written data to the socket, it is in the kernel buffer, where it will remain until it is sent and acknowledged. Shutting down does not result in loss of buffered data. Closing a socket does not cause buffered data to be lost. Even the death of the sending process will not cause fading data to fade.

You can observe the buffer size with netstat . The SendQ column is the amount of data that the kernel still wants to transmit.

After the client confirmed everything, the port disappeared from the server. This can happen before the client reads the data, in which case it will be in RecvQ on the client. Basically, you have nothing to worry about. After successfully writing to the TCP socket, each component tries its best to ensure that your data hits the target unscathed, regardless of what happens to the sending socket and / or process.

Well, maybe one thing to worry about: if a client tries to send something after the server shuts down, it can get SIGPIPE and die before it reads all available data from the socket.

+2
source

Source: https://habr.com/ru/post/922493/


All Articles