标签:soc rar sizeof 支持 sele ndt read nbsp unsigned
用select实现超时
1.read_timeout函数封装
2.write_timeout
3.accept_timeout
4.connect_timeout
套接字I/O超时设置方法
1.ararm
第一种:
SIGALRM
void handler(int sig)
{
return 0;
}
signal(SIGLRM,handler);
alarm(5);
int ret =read(fd,buf,sizeof(buf));
if(ret== -1&&errno == EINET)
{
errno = ETIMEOUT;
}else if (ret>=0)
{
alarm(0);
}
第二种
sctsockopt(sock, SOL_SOCKET, SO_RECVTIMEO,5);
int ret = read(sock, buf, sizeof(buf));
if(ret == -1&&errno = EWOULLBLOCK)
{
errno = ETIMEOUT;
}// 有些时候不支持
2.套接字选项
1) SO_SNDTIMEO
2) SO_RCVTIMEO
a) read_timeout(int fd, unsigned int wait_seconds )
逻辑: 读超时检测函数(不含读操作)
成功(未超时),返回0;
失败 /超时-1 且 errno = ETIMEOUT;
int ret = read_timeout(fd, 5);
if (ret ==0)
{
read(fd...);
}
else if(ret==-1)
{
timeout...
}else
{
ERR_EXIT("read_timeout");
}
b) write_timeout 同理(不含写操作)
c) accept_timeout 带超时的accept
成功返回已连接的套接字,超市返回-1且errno = ETIMEOUT
accept_timeout (int fd , struct sockaddr_in *addr. unsigned int wait_seconds)
d)connect-timeout
connect_timeout (int fd, struct sockaddr_in *addr, unsigned int wait_seconds)
addr: 要连接的对方的地址
成功返回0 , 失败返回-1且errno = ETIMEOUT
如果waite_seconds>0就改成非阻塞模式,调用connect_timeout
获取错误信息:调用getsockopt()
int err;
socklen_t socklen = sizeof(err);
int sockoptret = getsockopt(fd , SOL_SOCKET, SO_ERROR, &err, &socklen);
if (sockoptret == -1)
return -1;
if(err ==0)
ret=0;
else
{
errno =err;
ret =-1;
}
最后处理完成还要返回ret 的值
标签:soc rar sizeof 支持 sele ndt read nbsp unsigned
原文地址:https://www.cnblogs.com/Begin-Again/p/12571023.html