Linux-Network C Programming epoll function, linux-cepoll

Source: Internet
Author: User

Linux-Network C Programming epoll function, linux-cepoll

As mentioned above, epoll is equivalent to a mobile phone if take-out is taken from different places of 100. When the take-out arrives, the deliveryman can notify you so that each take-out can go a lot less.
How does it implement these functions?

Epoll Functions

Epoll is a strong version of select/poll. It is also a multiplexing function, and epoll has been greatly improved.

In a process, select can open fd is limited, set by the macro FD_SETSIZE, the default value is 1024. In some cases, this value is far from enough. There are two solutions: one is to modify the macro and then re-compile the kernel, but at the same time it will cause a decline in network efficiency; the other is to use multi-process solutions, however, creating multiple processes is costly, and data synchronization between processes is not convenient among multiple threads.
Epoll does not have this limit. It supports a maximum of 1024 FD, it is about 0.1 million on a machine with 1 GB of memory (the specific number can be viewed in cat/proc/sys/fs/file-max );

Each time a select function listens to a socket group, it returns a result when an event is generated, but it cannot filter the socket generated by the event, but changes the flag of the event in the socket group, therefore, each time you listen to an event, you need to traverse the entire set. The time complexity is O (n ). When the number of FD increases, the efficiency will decrease linearly.
Epoll adds the socket that generates the event from the listening string to the list each time. Then, we can directly operate on the list, and the socket that does not generate the event will be filtered out, IO efficiency is greatly improved. This is especially evident when the number of socket listeners is large and the number of active sockets is small.

Epoll usage

Epoll mainly uses three functions.

1. epoll_create (int size );

Create an epoll handle and the size is used to tell the kernel the maximum number of this listener. Note! It is the maximum number, not the maximum value of fd. Do not confuse it. After the epoll handle is created, it occupies an fd value. Therefore, you must call close () after epoll is used. Otherwise, the fd may be exhausted.

2. int epoll_ctl (int epfd, int op, int fd, struct epoll_event * event );

Epoll event registration function. Epfd is the epoll handle, that is, the returned value of epoll_create; op indicates the action: use three macros: EPOLL_CTL_ADD: register a new fd to epfd; EPOLL_CTL_MOD: modify the listening event of the registered fd; EPOLL_CTL_DEL: delete an fd from epfd; fd is the socket descriptor to be listened to; event is the struct that sets the listening event. The data structure is as follows:
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 can be a collection of the following macros: EPOLLIN: indicates that the corresponding file descriptor can be read (including the normal shutdown of the Peer SOCKET); EPOLLOUT: indicates that the corresponding file descriptor can be written; EPOLLPRI: indicates that the corresponding file descriptor has an urgent readable data (Here it should indicate that there is an out-of-band data arrival); EPOLLERR: indicates that the corresponding file descriptor has an error; EPOLLHUP: indicates that the corresponding file descriptor is hung up; EPOLLET: sets EPOLL to Edge Triggered mode, which is relative to Level Triggered. EPOLLONESHOT: only listens for an event once. After listening for this event, the fd will be deleted from the epoll queue. If you want to continue listening to this socket, you need to add this fd to the EPOLL queue again.

3. int epoll_wait (int epfd, struct epoll_event * events, int maxevents, int timeout );

Wait for the event to be generated, return the number of events to be processed, and set the socket for the event to be processed in the events parameter. You can traverse events to process the event. The epfd parameter is the epoll handle. events indicates that the timeout parameter of the event set is the timeout time (in milliseconds, 0 is returned immediately, and-1 is permanently blocked ). This function returns the number of events to be processed. If 0 is returned, the Operation has timed out.

Example of using a function

# Include <sys/socket. h> # include <sys/epoll. h> # include <netinet/in. h> # include <arpa/inet. h> # include <fcntl. h> # include <unistd. h> # include <stdio. h> # include <errno. h> # include <stdlib. h> # include <string. h> # define MAXLINE 10 // maximum length # define OPEN_MAX 100 # define LISTENQ 20 # define SERV_PORT 8000 # define INFTIM 1000 # define IP_ADDR "10.73.219.151" int main () {struct epoll_event ev, events [20]; struct sockaddr_in clientaddr, serveraddr; int epfd; int listenfd; // listen to fd int maxi; int nfds; int I; int sock_fd, conn_fd; char buf [MAXLINE]; epfd = epoll_create (256); // generate the epoll handle listenfd = socket (AF_INET, SOCK_STREAM, 0); // create the socket ev. data. fd = listenfd; // sets the file descriptor ev associated with the event to be processed. events = EPOLLIN; // set the event type epoll_ctl (epfd, EPOLL_CTL_ADD, listenfd, & ev) to be processed; // register the epoll event memset (& serveraddr, 0, sizeof (serveraddr); serveraddr. sin_family = AF_INET; serveraddr. sin_addr.s_addr = htonl (INADDR_ANY); serveraddr. sin_port = htons (SERV_PORT); bind (listenfd, (struct sockaddr *) & serveraddr, sizeof (serveraddr); // bind the interface socklen_t clilen; listen (listenfd, LISTENQ ); // switch to listening socket int n; while (1) {nfds = epoll_wait (epfd, events, 20,500 ); // wait for the event to occur // process all events that occur for (I = 0; I <nfds; I ++) {if (events [I]. data. fd = listenfd) // There is a new connection {clilen = sizeof (struct sockaddr_in); conn_fd = accept (listenfd, (struct sockaddr *) & clientaddr, & clilen ); printf ("accept a new client: % s \ n", inet_ntoa (clientaddr. sin_addr); ev. data. fd = conn_fd; ev. events = EPOLLIN; // set the listening event to writable epoll_ctl (epfd, EPOLL_CTL_ADD, conn_fd, & ev); // Add socket} else if (events [I]. events & EPOLLIN) // read event {if (sock_fd = events [I]. data. fd) <0) continue; if (n = recv (sock_fd, buf, MAXLINE, 0) <0) {if (errno = ECONNRESET) {close (sock_fd ); events [I]. data. fd =-1;} else {printf ("readline error \ n") ;}} else if (n = 0) {close (sock_fd ); printf ("Disable \ n"); events [I]. data. fd =-1;} printf ("% d --> % s \ n", sock_fd, buf); ev. data. fd = sock_fd; ev. events = EPOLLOUT; epoll_ctl (epfd, EPOLL_CTL_MOD, sock_fd, & ev); // modify the listening event to readable} else if (events [I]. events & EPOLLOUT) // writable event {sock_fd = events [I]. data. fd; printf ("OUT \ n"); scanf ("% s", buf); send (sock_fd, buf, MAXLINE, 0); ev. data. fd = sock_fd; ev. events = EPOLLIN; epoll_ctl (epfd, EPOLL_CTL_MOD, sock_fd, & ev) ;}} return 0 ;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.