一、POLL/SELECT 方式的功能:
SELECT 机制、POLL 机制是完全一样的,只是 APP 接口函数不一样。
在调用 poll , select 函数时可以 传入“超时时间” ,相当于“定个闹钟”。在这段时间内,如果又数据可读,有空间可写等,就会立即返回,否则等到“超时时间”结束时就会返回错误。
poll, select 函数可以检测 多个文件,多种事件。
二、select 机制:
1. select 函数原型:
头文件 :#include <sys/select.h>
函数原型
int select ( int nfds , fd_set * readfds , fd_set * writefds , fd_set * exceptfds , struct timeval * timeout ) ;
2. select 有三种返回值:
① 返回 -1 ,表明出错了,出现异常。
② 返回 0, 最大时间已超时。
③ 返回 正数,有文件可以提供数据了。
3. fd_set:
fd_set 是一组文件描述符 ( fd ) 的集合,实际上是一个 long 类型的数组,它用一位表示一个 fd 。
现在,UNIX系统中通常会定义常量 FD_SETSIZE 来表示 fd_set 的描述符数量。其值通常是1024,这样就能表示1024个fd。
fd_set FDs; 1 typedef __kernel_fd_set fd_set; 1 #define __FD_SETSIZE 1024 typedef struct { unsigned long fds_bits[__FD_SETSIZE / (8 * sizeof(long))]; } __kernel_fd_set;
我们可以使用以下四个宏来操作 fd_set :
FD_ZERO(fd_set* fdset): 对其进行初始化, 将指定的文件描述符集清空, fd_set 变量的所有位初始化为0。 FD_SET(int fd, fd_set* fdset):在文件描述符集合 fdset 中增加一个新的文件描述符 fd , 注册文件描述符 fd 的信息。 FD_CLR(int fd, fd_set* fdset):在文件描述符集合 fdset 中删除一个文件描述符 fd。 FD_ISSET(int fd, fd_set* fdset):测试指定的文件描述符 fd 是否在该集合 fdset 中,包含文件描述符 fd 的信息,则返回真。
4. select 各参数含义:
① nfds :所有文件描述符中的最大值 +1.
② readfds :需要检测的 可读 文件描述符的集合。
③ writefds :需要检测的 可写 文件描述符的集合。
④ exceptfds :需要检测的 异常 文件描述符的集合。
⑤ timeout :最大 超时时间 。
5.struct timeval:
struct timeval 结构体用于指定更精确的时间值,秒,微妙。
struct timeval { __kernel_time_t tv_sec; /* seconds */ __kernel_suseconds_t tv_usec; /* microseconds */ };
总结
一般 POLL 机制的使用较多,但是 SELECT 机制也是比较重要的,还有一些SELECT 机制比较巧妙的功能,我们下次再为大家分享。