今天没有系统学习什么新知识,就是把以前学到的知识复习了一下,其中有几点值得注意
connect(fd, (struct sockaddr *)addr, sizeof(struct sockaddr_in));
当fd处于非阻塞时, 如果connect没有成功连接,将返回-1,errno将指定于EINPROGRESS,意思是连接仍然在继续.
这个时候就可以用select来检测fd的状态了,一旦fd可写时,代表连接建立好,配合select实现了connect的连接超时设定的问题
select的返回值,
大于0,代表有n个监控的描述符"准备好",读写这些描述符均不会阻塞.
等于0,超时
小于0,发生错误,errno被指定
int write_timeout(int fd, unsigned int wait_seconds) { int ret = 0; //初始条件检查 if (fd < 0 || wait_seconds <= 0) { ret = -1; printf("func write_timeout()err:%d ", ret); return ret; } fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(fd, &rfds); tv.tv_sec = 3; tv_usec = 0; do { ret = select(fd + 1, NULL, &rfds, NULL, &tv); }while(-1 == ret && errno == EINTR); //如果被信号打断,可以再次检测 if (0 == ret) { ret = -1; errno = ETIMEDOUT; } else if (1 == ret) ret = 0; return ret; }
.