1.设置套接字为非阻塞模式 int fcntl(int fd,int cmd,long arg);
2.初始化描述符集 void FD_ZERO(fd_set *fdset);
3.将一个描述符添加到描述符集 void FD_SET(int fd, fd_set *fdset);
4.将一个描述符从描述符集中删除 void FD_CLR(int fd, fd_set *fdset);
5.检测指定的描述符是否有事件发生 int FD_ISSET(int fd, fd_set *fdset);
示例:
fd_set rset;//创建一个描述符集rset
FD_ZERO(&rset);//对描述符集rset清零
FD_SET(0, &rset);//将描述符0加入到描述符集rset中
FD_SET(4, &rset);//将描述符4加入到描述符集rset中
FD_SET(5, &rset);//将描述符5加入到描述符集rset中
6.select函数
int select(int maxfd, fd_set *readset, fd_set *writeset, fd_set *exceptset, const struct timeval *timeout);
返回值为0超时、返回值为-1出错,返回值大于0表示准备好的文件描述符数量
maxfd 指定要检查的描述符的范围,所检测描述符最大值+1
readset 读描述符集
writeset 写描述符集
exceptset 异常描述符集,带外数据,一般NULL
timeout 超时时间,超过规定时间后唤醒
struct timeval{
long tv_sec;//秒
long tv_usec;//微秒
};
//比如等待10.2秒
struct timeval timeout;
timeoout.tv_sec = 10;
timeoout.tv_usec = 200000;