The close () function is called when a TCP connection is disconnected in Linux. There are two methods: elegant disconnection and forced disconnection.
So how do I set the disconnection mode? Is to set a linger struct attribute of the socket descriptor.
The data structure of the linger struct is as follows:
# Include <ARPA/inet. h>
Struct linger {
Int l_onoff;
Int l_linger;
};
Three disconnection methods:
1. l_onoff = 0; l_linger ignore
Close () returns immediately. The underlying layer will release the resources after sending the unsent data, that is, exit gracefully.
2. l_onoff! = 0; l_linger = 0;
Close () returns immediately, but does not Send unsent data. Instead, it forces the socket descriptor to be closed through a rest package, that is, force exit.
3. l_onoff! = 0; l_linger> 0;
Close () will not return immediately, and the kernel will be delayed for a period of time, which is determined by the value of l_linger. If the time-out period reaches, the unsent data (including the fin package) is sent and the confirmation from the other end is obtained, close () returns the correct result, and the socket descriptor exits elegantly. Otherwise, close () will directly return an error value. If no data is sent, the socket descriptor is forcibly exited. Note that if the socket descriptor is set to a non-blocking type, close () will return the value directly.
Usage:
Struct linger Ling = {0, 0 };
Setsockopt (socketfd, sol_socket, so_linger, (void *) & Ling, sizeof (Ling ));