Http://www.embedu.org/Column/Column208.htm
Author: Zeng Hongan,Hua Qing vision embedded college lecturer.
A common method in network programming is: after a socket is created, it is read and written in a blocking manner. If no data is readable, the program will wait. As a matter of fact, network conditions have been constantly changing and it is very likely that network connections are disconnected during communication. We need to detect this situation in the program to respond in a timely manner. The following describes several common timeout detection methods (assuming that the maximum time required to wait for data through a socket is 8 seconds ):
1. Set socket receiving timeout
Setsockopt can set the properties of the socket, including the receiving timeout time. The reference code is as follows:
Struct timeval TV; // struct variable that describes the time
......
TV. TV _sec = 8;
TV. TV _usec = 0;
Setsockopt (sockfd, sol_socket, so_rcvtimeo, & TV, sizeof (TV ));
......
Ii. Multi-Channel Io multiplexing select
The select function is usually used to implement multi-channel Io multiplexing and can also be used to implement timeout processing. The reference code is as follows:
Struct timeval TV; // struct variable that describes the time
Fdset rdfds; // defines a set of read descriptors.
......
TV. TV _sec = 8;
TV. TV _usec = 0;
Fd_zero (& rdfds );
Fd_set (sockfd, & rdfds );
If (select (sockfd + 1, & rdfds, null, null, & TV) = 0)
{
Timeout Processing
}
......
3. Set a timer
The principle of this method is to set an 8-second timer before receiving data from the socket. If no data arrives within 8 seconds, the sigalrm signal generated by the kernel will interrupt the current read operation. We know that the signal capturing function can be set using the signal function or the sigaction function. However, only the sigaction function can be used here, because the interrupted operation will be re-executed after the signal processing function set by signal is executed. The reference code is as follows:
Void handler (INT signo) // custom sigalrm Signal Processing Function
{
Return;
}
Struct sigaction Act; // variable that describes signal behavior
......
Sigaction (sigalrm, null, & Act); // gets the sigalrm signal attribute
Act. sa_handler = handler; // sets the processing function of the sigalrm signal.
Act. sa_flags & = ~ Sa_restart; // the option for stopping restart
Sigaction (sigalrm, & act, null); // you can specify the sigalrm signal attribute.
Alarm (8); // sets an 8-second timer.
......
Although we use the read operations on sockets as an example, in fact, in many similar cases, you can take the method described above as appropriate. Clever use of the knowledge will make your program more flexible and humane.