网络超时检测

getsockopt
setsockopt
网络超时检测:
必要性:避免进程在没有数据时无限制的阻塞
当设置的时间到,进程从原操作返回继续运行
3种方式可以:
1.设置socket的属性
SO_RCVTIMEO 接收超时
SO_SNDTIMEO 发送超时

struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv));
5秒接收超时检测。

2.select也可以超时检测

3.设置定时器(timer),捕捉SIGALRM信号

#include <stdio.h>
#include <signal.h>

void handler(int sig)
{
printf("sig = %d\n", sig);
}

int main()
{
char buf[100] = "hello";
//signal(SIGALRM, handler);
struct sigaction myaction;
sigaction(SIGALRM, NULL, &myaction);
myaction.sa_handler = handler;
myaction.sa_flags &= ~SA_RESTART;
//myaction.sa_flags |= SA_RESTART;
sigaction(SIGALRM, &myaction, NULL);


while(1)
{
alarm(2);
if(fgets(buf, 100, stdin) == NULL)
{
//continue;
break;
}
alarm(0);
printf("buf = %s\n", buf);
}

 

}

 

posted on 2012-07-06 20:32  孟浩依然  阅读(583)  评论(0编辑  收藏  举报