Usage of struct linger

Source: Internet
Author: User

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 ));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.