#include<sys/select.h>
int select(int nfds,fd_set*readfds,fd_set*writefds,fd_set*exceptfds,struct timeval*timeout);
参数:
struct timeval
{
long tv_sec;/*秒数*/
long tv_usec;/*微秒数*/
};
返回值:成功返回就绪文件描述符总数;失败或收到信号返回-1
注意:对方关闭连接,该socket读操作符返回0
fd_set操作
#include<sys/select.h>
FD_ZERO(fd_set*fdset);/*清除fdset的所有位*/
FD_SET(int fd,fd_set*fdset);/*设置fdset的位fd*/
FD_CLR(int fd,fd_set*fdset);/*清除fdset的位fd*/
int FD_ISSET(int fd,fd_set*fdset);/*测试fdset的位fd是否被设置*/
pool:机制与select类似
#include<poll.h>
int poll(struct pollfd*fds,nfds_t nfds,int timeout);
参数:
struct pollfd
{
int fd;/*文件描述符*/
short events;/*注册的事件,一系列事件的按位或*/
short revents;/*实际发生的事件,由内核填充*/
};
timeout为-1时,poll调用将永远阻塞,直到某个事件发生;当timeout为0时,poll调用将立即返回。
返回值:同select
epoll系统调用:epoll把用户关心的文件描述符上的事件放在内核里的一个事件表
内核事件表
创建树
#include<sys/epoll.h>
int epoll_create(int size)
参数:size参数不起作用
控制树
#include<sys/epoll.h>
int epoll_ctl(int epfd,int op,int fd,struct epoll_event*event)
参数:
epfd:创建树的返回值
op:
EPOLL_CTL_ADD,往事件表中注册fd上的事件。
EPOLL_CTL_MOD,修改fd上的注册事件。EPOLL_CTL_DEL,删除fd上的注册事件。
struct epoll_event
{
__uint32_t events;/*epoll事件*/
epoll_data_t data;/*用户数据*/
};
typedef union epoll_data
{
void*ptr;
int fd;
uint32_t u32;
uint64_t u64;
}epoll_data_t;
epoll_wait函数:一段超时时间内等待一组文件描述符上的事件
#include<sys/epoll.h>
int epoll_wait(int epfd,struct epoll_event*events,int maxevents,int timeout);
实例:
/*如何索引epoll返回的就绪文件描述符*/
int ret=epoll_wait(epollfd,events,MAX_EVENT_NUMBER,-1);
/*仅遍历就绪的ret个文件描述符*/
for(int i=0;i<ret;i++)
{
int sockfd=events[i].data.fd;
/*sockfd肯定就绪,直接处理*/
}