4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <arpa/inet.h>
13 #include <netinet/in.h>
14 #include <sys/socket.h>
15 #include <sys/epoll.h>
16
17 /* 最缓存区 */
18 #define MAX_BUFFER_SIZE 5
19 /* epoll最监听数 */
20 #define MAX_EPOLL_EVENTS 20
21 /* LT模式 */
22 #define EPOLL_LT 0
23 /* ET模式 */
24 #define EPOLL_ET 1
25 /* 件描述符设置阻塞 */
26 #define FD_BLOCK 0
27 /* 件描述符设置阻塞 */
28 #define FD_NONBLOCK 1
29
30 /* 设置件为阻塞 */
31 int set_nonblock(int fd)
32 {
33 int old_flags = fcntl(fd, F_GETFL);
34 fcntl(fd, F_SETFL, old_flags | O_NONBLOCK);
35 return old_flags;
36 }
37
38 /* 注册件描述符到epoll,并设置其事件为EPOLLIN(可读事件) */
39 void addfd_to_epoll(int epoll_fd, int fd, int epoll_type, int block_type)
40 {
41 struct epoll_event ep_event;
42 ep_event.data.fd = fd;
43 ep_event.events = EPOLLIN;
44
45 /* 如果是ET模式,设置EPOLLET */
46 if (epoll_type == EPOLL_ET)
47 ep_event.events |= EPOLLET;
48
49 /* 设置是否阻塞 */
50 if (block_type == FD_NONBLOCK)
51 set_nonblock(fd);