网络超时检测相关知识
  • 何为网络超时检测:
  • 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);/*其中,最后一个参数,就是超时时间NULL   永久阻塞struct timeval  	可以指定超时时间如果结构体的两个成员都为0 表示非阻塞返回值:成功  	就绪的文件描述符的个数失败  	-1超时  	0*/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)}
  • 方法三 :
  • 设置取消SIGALRM的自重启属性:
	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); //再重新设置回去
  • 信号定时器函数(alarm函数):
	#include <unistd.h>unsigned int alarm(unsigned int seconds);/*功能:在指定的秒数到达后,给当前进程发一个SIGALRM信号如果seconds为0 则不发信号参数:seconds:倒计时的秒数返回值:如果之前没有调用过alarm 则返回0如果之前调用过alarm 则返回剩余的秒数*/
  • SIGALRM:该信号用于通知进程定时器时间已到;