linux c/c++开发的同志们一定要掌握select函数,因为它简单高效。以下是本人开发中遇到的几个问题。
一、函数原型
int select(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout);
参数解析:
nfds:最大监听fd数,一般是最大文件号加1
readfds:可读文件句柄集合。
writefds:可写文件句柄集合。
exceptfds:异常文件句柄集合。
timeout:NULL表示阻塞,非NULL可精确到微妙级别。
二、高级用途
1、监听句柄的读写事件
2、实现非租塞模型服务器
3、实现线程安全的sleep
三、使用实例
1.监听可读事件
int is_fd_can_read(int fd, long usec){
struct timeval timeOut;
bzero(&timeOut,sizeof(timeOut));
timeOut.tv_sec = usec/1000000;
timeOut.tv_usec = usec%1000000;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd,&rfds);
int rv=select(fd+1, &rfds, NULL, NULL, &timeOut);
return rv>0?1:0;
}
注意:以上函数在fd取值在0到1152可正常监听可读事件,但是当fd等于1154时FD_SET() 则