何为网络超时检测: 1、介于阻塞与非阻塞之间; 2、设置一个时间,时间结束前,若缓冲区无数据,就阻塞; 3、时间结束后,若缓冲区仍未有数据,就切换为非阻塞的状态; 如何实现: 1、设定select函数的最后一个参数实现超时处理; 2、通过setsockopt设置套接字属性,一次设置,终身有效; 3、设置信号定时器函数(alarm函数),捕捉SIGALRM信号; 方法一:
# include <sys/select.h> int select ( int nfds, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout) ; struct timeval { long tv_sec; long tv_usec; } ;
struct timeval tm; tm. tv_sec = 10 ; tm. tv_usec = 0 ; if ( - 1 == setsockopt ( sockfd, SOL_SOCKET, SO_RCVTIMEO, & tm, sizeof ( tm) ) ) { perror ( "setsockopt error" ) ; exit ( - 1 ) }
void sig_func ( int signum) { printf ( "I Love China!!!\n" ) ; }
struct sigaction action; sigaction ( SIGALRM, NULL , & action) ; action. sa_flags &= ~ SA_RESTART; action. sa_handler = sig_func; sigaction ( SIGALRM, & action, NULL ) ;
# include <unistd.h> unsigned int alarm ( unsigned int seconds) ;
SIGALRM :该信号用于通知进程定时器时间已到;