linux网络编程之socket(十三):epoll 系列函数简介、与select、poll 的区别

一、epoll 系列函数简介

#include <sys/epoll.h>
int epoll_create(int size);
int epoll_create1(int flags);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);


       *  epoll_create(2)  creates  an epoll instance and returns a file descriptor referring to that instance.  (The more recent
          epoll_create1(2) extends the functionality of epoll_create(2).)


       *  Interest in particular file descriptors is then registered via epoll_ctl(2).  The set  of  file  descriptors  currently
          registered on an epoll instance is sometimes called an epoll set.


       *  epoll_wait(2) waits for I/O events, blocking the calling thread if no events are currently available.


1、epoll_create1 产生一个epoll 实例,返回的是实例的句柄。flag 可以设置为0 或者EPOLL_CLOEXEC,为0时函数表现与epoll_create一致,EPOLL_CLOEXEC标志与open 时的O_CLOEXEC 标志类似,即进程被替换时会关闭打开的文件描述符。

2、epoll_ctl :

(1)epfd:epoll 实例句柄;

(2)op:对文件描述符fd 的操作,主要有EPOLL_CTL_ADD、 EPOLL_CTL_DEL等;

(3)fd:需要操作的目标文件描述符;

(4)event:结构体指针

  typedef union epoll_data {
               void        *ptr;
               int          fd;
               uint32_t     u32;
               uint64_t     u64;
           } epoll_data_t;

 struct epoll_event {
          uint32_t     events;      /* Epoll events */
                epoll_data_t  data;        /* User data variable */
           };

events 参数主要有EPOLLIN、EPOLLOUT、EPOLLET、EPOLLLT等;一般data 共同体我们设置其成员fd即可,也就是epoll_ctl 函数的第三个参数。

3、epoll_wait:

(1)epfd:epoll 实例句柄;

(2)events:结构体指针

(3)maxevents:事件的最大个数

(4)timeout:超时时间,设为-1表示永不超时


下面我们使用c++ 来实现一个服务器端程序:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值