标签:占用 efi cti 更改 队列 文件描述符 create 进程id char
epoll
是Linux内核中的一种可扩展IO事件处理机制,最早在 Linux 2.5.44内核中引入,可被用于代替POSIX select 和 poll 系统调用,并且在具有大量应用程序请求时能够获得较好的性能( 此时被监视的文件描述符数目非常大,与旧的 select 和 poll 系统调用完成操作所需 O(n) 不同, epoll能在O(1)时间内完成操作,所以性能相当高),epoll 与 FreeBSD的kqueue类似,都向用户空间提供了自己的文件描述符来进行操作。
int epoll_create(int size);
创建一个epoll的句柄,size用来告诉内核需要监听的数目一共有多大。当创建好epoll句柄后,它就是会占用一个fd值,在linux下如果查看/proc/进程id/fd/,是能够看到这个fd的,所以在使用完epoll后,必须调用close() 关闭,否则可能导致fd被耗尽。
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
epoll的事件注册函数,第一个参数是 epoll_create() 的返回值,第二个参数表示动作,使用如下三个宏来表示:
EPOLL_CTL_ADD //注册新的fd到epfd中; EPOLL_CTL_MOD //修改已经注册的fd的监听事件; EPOLL_CTL_DEL //从epfd中删除一个fd;
第三个参数是需要监听的fd,第四个参数是告诉内核需要监听什么事,struct epoll_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 //表示对应的文件描述符可以读(包括对端SOCKET正常关闭); EPOLLOUT //表示对应的文件描述符可以写; EPOLLPRI //表示对应的文件描述符有紧急的数据可读(这里应该表示有带外数据到来); EPOLLERR //表示对应的文件描述符发生错误; EPOLLHUP //表示对应的文件描述符被挂断; EPOLLET //将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(Level Triggered)来说的。 EPOLLONESHOT//只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里。
当对方关闭连接(FIN), EPOLLERR,都可以认为是一种EPOLLIN事件,在read的时候分别有0,-1两个返回值。
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
参数epfd是epoll_create返回的句柄,events用来从内核得到事件的集合,maxevents 告之内核这个events有多大,这个 maxevents 的值不能大于创建 epoll_create() 时的size,参数 timeout 是超时时间(毫秒,0会立即返回,-1将不确定,也有说法说是永久阻塞)。该函数返回需要处理的事件数目,如返回0表示已超时。
EPOLL事件有两种模型 Level Triggered (LT) 和 Edge Triggered (ET):
LT(level triggered,水平触发模式)是缺省的工作方式,并且同时支持 block 和 non-block socket。在这种做法中,内核告诉你一个文件描述符是否就绪了,然后你可以对这个就绪的fd进行IO操作。如果你不作任何操作,内核还是会继续通知你的,所以,这种模式编程出错误可能性要小一点。
ET(edge-triggered,边缘触发模式)是高速工作方式,只支持no-block socket。在这种模式下,当描述符从未就绪变为就绪时,内核通过epoll告诉你。然后它会假设你知道文件描述符已经就绪,并且不会再为那个文件描述符发送更多的就绪通知,等到下次有新的数据进来的时候才会再次出发就绪事件。
teacher‘s
#include <stdio.h> #include <stdio.h> #include "debug.h" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <poll.h> #include <sys/epoll.h> int main() { int listenfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == listenfd) errsys("socket"); struct sockaddr_in myaddr = {0}; struct sockaddr_in clientaddr = {0}; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(8888); myaddr.sin_addr.s_addr = inet_addr("0.0.0.0");//INADDR_ANY int len = sizeof myaddr; if(-1 == bind(listenfd, (struct sockaddr*)&myaddr, len)) errsys("bind"); if(-1 == listen(listenfd, 10)) errsys("listen"); int epoll_fd = epoll_create(1024); //创建epoll句柄,最大监听1024个事件 if(-1 == epoll_fd) errsys("epoll"); struct epoll_event event = {0}; event.events = EPOLLIN; //监听读取是否准备就绪 event.data.fd = listenfd; //要监听的是 listen sockt epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listenfd, &event); //注册一个listen 监听事件 #define BUFSIZE 100 #define MAXNFD 1024 struct epoll_event revents[MAXNFD] = {0}; //用来存放就绪的监听事件 int nready; char buf[MAXNFD][BUFSIZE] = {0}; while(1) { if(-1 == (nready = epoll_wait(epoll_fd, revents, MAXNFD, -1)) ) //开始监听事件,返回就绪事件数,就绪事件存放到 revents 低下标开始的位置, //从返回0超时, 返回-1,出错 errsys("poll"); int i = 0; for(;i<nready; i++) //遍历就绪事件 { if(revents[i].events & EPOLLIN) //server读请求就绪 { if(revents[i].data.fd == listenfd) //读请求来自于client; { int sockfd = accept(listenfd, (struct sockaddr*)&clientaddr, &len); //获取client 套接字 if(-1 == sockfd) errsys("accept"); debug("incoming: %s\n", inet_ntoa( clientaddr.sin_addr) ); struct epoll_event event = {0}; event.events = EPOLLIN; event.data.fd = sockfd; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &event); //注册事件,用于 监听 client 发送请求是否就绪 } else { int ret = read(revents[i].data.fd, buf[revents[i].data.fd], sizeof buf[0]); //从client 读取 if(0 == ret) //client 关闭 { close(revents[i].data.fd); epoll_ctl(epoll_fd, EPOLL_CTL_DEL, revents[i].data.fd, &revents[i]); //注销监听事件 } revents[i].events = EPOLLOUT; //读取数据后,读操作请求监听 修改为 server写操作请求就绪监听 epoll_ctl(epoll_fd, EPOLL_CTL_MOD, revents[i].data.fd, &revents[i]); } } else if(revents[i].events & EPOLLOUT) // server 写请求就绪 { int ret = write(revents[i].data.fd, buf[revents[i].data.fd], sizeof buf[0]); printf("ret %d: %d\n", revents[i].data.fd, ret); revents[i].events = EPOLLIN; epoll_ctl(epoll_fd, EPOLL_CTL_MOD, revents[i].data.fd, &revents[i]); //更改监听事件为 读client 请求 } } } close(listenfd); }
我们将实现一个简单的TCP 服务器,该迷你服务器将会在标准输出上打印处客户端发送的数据,首先我们创建并绑定一个 TCP 套接字:
static int create_and_bind (char *port) { struct addrinfo hints; struct addrinfo *result, *rp; int s, sfd; memset (&hints, 0, sizeof (struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ hints.ai_flags = AI_PASSIVE; /* All interfaces */ s = getaddrinfo (NULL, port, &hints, &result); if (s != 0) { fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (s)); return -1; } for (rp = result; rp != NULL; rp = rp->ai_next) { sfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sfd == -1) continue; s = bind (sfd, rp->ai_addr, rp->ai_addrlen); if (s == 0) { /* We managed to bind successfully! */ break; } close (sfd); } if (rp == NULL) { fprintf (stderr, "Could not bind\n"); return -1; } freeaddrinfo (result); return sfd; }
create_and_bind() 包含了如何创建 IPv4 和 IPv6 套接字的代码块,它接受一字符串作为端口参数,并在 result 中返回一个 addrinfo 结构,
struct addrinfo
{
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
如果函数成功则返回套接字,如果失败,则返回 -1,
下面,我们将一个套接字设置为非阻塞形式,函数如下:
static int
make_socket_non_blocking (int sfd)
{
int flags, s;
flags = fcntl (sfd, F_GETFL, 0);
if (flags == -1)
{
perror ("fcntl");
return -1;
}
flags |= O_NONBLOCK;
s = fcntl (sfd, F_SETFL, flags);
if (s == -1)
{
perror ("fcntl");
return -1;
}
return 0;
}
接下来,便是主函数代码,主要用于事件循环:
#define MAXEVENTS 64
int
main (int argc, char *argv[])
{
int sfd, s;
int efd;
struct epoll_event event;
struct epoll_event *events;
if (argc != 2)
{
fprintf (stderr, "Usage: %s [port]\n", argv[0]);
exit (EXIT_FAILURE);
}
sfd = create_and_bind (argv[1]);
if (sfd == -1)
abort ();
s = make_socket_non_blocking (sfd);
if (s == -1)
abort ();
s = listen (sfd, SOMAXCONN);
if (s == -1)
{
perror ("listen");
abort ();
}
efd = epoll_create1 (0);
if (efd == -1)
{
perror ("epoll_create");
abort ();
}
event.data.fd = sfd;
event.events = EPOLLIN | EPOLLET;
s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);
if (s == -1)
{
perror ("epoll_ctl");
abort ();
}
/* Buffer where events are returned */
events = calloc (MAXEVENTS, sizeof event);
/* The event loop */
while (1)
{
int n, i;
n = epoll_wait (efd, events, MAXEVENTS, -1);
for (i = 0; i < n; i++)
{
if ((events[i].events & EPOLLERR) ||
(events[i].events & EPOLLHUP) ||
(!(events[i].events & EPOLLIN)))
{
/* An error has occured on this fd, or the socket is not
ready for reading (why were we notified then?) */
fprintf (stderr, "epoll error\n");
close (events[i].data.fd);
continue;
}
else if (sfd == events[i].data.fd)
{
/* We have a notification on the listening socket, which
means one or more incoming connections. */
while (1)
{
struct sockaddr in_addr;
socklen_t in_len;
int infd;
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
in_len = sizeof in_addr;
infd = accept (sfd, &in_addr, &in_len);
if (infd == -1)
{
if ((errno == EAGAIN) ||
(errno == EWOULDBLOCK))
{
/* We have processed all incoming
connections. */
break;
}
else
{
perror ("accept");
break;
}
}
s = getnameinfo (&in_addr, in_len,
hbuf, sizeof hbuf,
sbuf, sizeof sbuf,
NI_NUMERICHOST | NI_NUMERICSERV);
if (s == 0)
{
printf("Accepted connection on descriptor %d "
"(host=%s, port=%s)\n", infd, hbuf, sbuf);
}
/* Make the incoming socket non-blocking and add it to the
list of fds to monitor. */
s = make_socket_non_blocking (infd);
if (s == -1)
abort ();
event.data.fd = infd;
event.events = EPOLLIN | EPOLLET;
s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);
if (s == -1)
{
perror ("epoll_ctl");
abort ();
}
}
continue;
}
else
{
/* We have data on the fd waiting to be read. Read and
display it. We must read whatever data is available
completely, as we are running in edge-triggered mode
and won‘t get a notification again for the same
data. */
int done = 0;
while (1)
{
ssize_t count;
char buf[512];
count = read (events[i].data.fd, buf, sizeof buf);
if (count == -1)
{
/* If errno == EAGAIN, that means we have read all
data. So go back to the main loop. */
if (errno != EAGAIN)
{
perror ("read");
done = 1;
}
break;
}
else if (count == 0)
{
/* End of file. The remote has closed the
connection. */
done = 1;
break;
}
/* Write the buffer to standard output */
s = write (1, buf, count);
if (s == -1)
{
perror ("write");
abort ();
}
}
if (done)
{
printf ("Closed connection on descriptor %d\n",
events[i].data.fd);
/* Closing the descriptor will make epoll remove it
from the set of descriptors which are monitored. */
close (events[i].data.fd);
}
}
}
}
free (events);
close (sfd);
return EXIT_SUCCESS;
}
main() 首先调用 create_and_bind() 建立套接字,然后将其设置为非阻塞的,再调用 listen(2)。之后创建一个epoll 实例 efd(文件描述符),并将其加入到sfd的监听套接字中以边沿触发方式等待事件输入。
外层的 while 循环是主事件循环,它调用了 epoll_wait(2),此时线程仍然被阻塞等待事件,当事件可用时,epoll_wait(2) 将会在events参数中返回可用事件。
epoll 实例 efd 在每次事件到来并需要添加新的监听时就会得到更新,并删除死亡的链接。
当事件可用时,可能有一下三种类型:
errno
会被设置成 EAGAIN
, 这意味着所有的数据已经被读取,可以返回主循环了。(全文完)
http://en.wikipedia.org/wiki/Epoll
https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/
http://blog.csdn.net/ljx0305/article/details/4065058
http://kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/
标签:占用 efi cti 更改 队列 文件描述符 create 进程id char
原文地址:http://www.cnblogs.com/chen-farsight/p/6031834.html