select (Unix)
![]() | 此條目包含過多行話或專業術語,可能需要簡化或提出進一步解釋。 (2012年11月29日) |
此條目没有列出任何参考或来源。 (2010年5月5日) |
select 是用于I/O多路转接的一个系统调用函数。 在C程序中,它被定义在 sys/select.h or unistd.h。 使用select要使用这些文件和 sys/time.h。
声明:
int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* errorfds, struct timeval* timeout);
参数 | 描述 |
---|---|
nfds | sets的文件描述符的最大值 |
readfds | fd_set type 类型,只读的描述符集 |
writefds | fd_set type 类型,只写的描述符集 |
errorfds | fd_set type 类型,错误的描述符集 |
timeout | 超时等待时间 |
为了维护fd_set类型的参数,会使用下面四个宏:FD_SET(), FD_CLR(), FD_ZERO() 和 FD_ISSET()。
返回值:
这个函数将返回描述符集的个数, 如果超时返回为0,错误则返回-1。
参看:
- select(2)
- poll(2)
select与epoll的区别
epoll | select | |
---|---|---|
概述 | epoll是个模块,由三个系统调用组成,内核中由用文件系统实现 | select是个系统调用 |
结构体定义 | typedef union epoll_data {
void *ptr; |
struct timeval{ long tv_sec;//second typedef struct fd_set |
可用的事件 | EPOLLIN :表示对应的文件描述符可以读; EPOLLOUT:表示对应的文件描述符可以写; |
fd_set有三种类型:
readfds, writefds, exceptionfds
|
操作函数 | 三个系统调用:epoll_create epoll_ctl epoll_wait | 一个系统调用:select 四个宏: FD_ZERO FD_SET FD_CLR FD_ISSET |
运行模式 | Edge Triggered (ET)、Lev Triggered (LT) | LT |
运行过程 | int fd = epoll_create(xxA); //xxA可监听的socket struct epoll_event events[xxxB];//可返回的事件数 int nfds = epoll_wait( ); //wait event occur }//end while |
struct timeval tv; fd_set rfds; FD_ZERO(&rfds); } //end while |
优点 | 1)epoll_wait返回的都是有效数据,可直接从struct epoll_event[]中获取事件,效率高。 | |
缺点 | 每次select有数据要遍历全部socket | |
注意事项 | 每次取事件后,要重新注册此socket的事件epoll。(epoll_ctl) | 每次select之前要重置rfds的值。(FD_ZERO) |
说明:以上无论epoll_create, fd_set都受限于系统中单个进程能够打开的文件句柄数。