A brief analysis of Epoll communication model under Linux

Source: Internet
Author: User

Epoll an I/O-based event notification mechanism, the system notifies the user that the sockets trigger those related I/O events, the event contains the corresponding file descriptor, and the event type, so that the application can handle the event and the source of the event accordingly (Acception,read , Write,error). Compared to the original select model (the user proactively checks the socket), the passive waiting system informs the active socket that performance is improved (no need to traverse all sockets in turn, but only event handling of the active socket).

Basic steps:

Be good at processing the request of a large number of concurrent users, and finish the data interaction between server and client. A simple implementation step is as follows:

(1) Create a listen socket:listensock, set the descriptor to non-blocking mode, and call the Listen () function to listen for connection requests on the socket.

(2) Use the Epoll_create () function to create a file description that sets the maximum number of socket descriptors that can be managed.

(3) Listensock registration into the epoll for monitoring

(4) Epoll monitoring starts, epoll_wait () waits for the Epoll event to occur.

(5) If the Epoll event indicates that there is a new connection request, call the Accept () function and add the newly established connection to the Epoll. If read-write or error, call the corresponding handle for processing.

(6) Continue monitoring until it stops.


The appeal process is only a simple linear example, in the actual application process, in order to improve the monitoring efficiency, often the epoll hear the incident to other specialized task threads for processing, in order to improve the efficiency of epoll monitoring.

Mainly related to API

1.EPoll creation

int epoll_create (int size)

The function generates a Epoll private file descriptor, where the parameter is the maximum range of the specified build descriptor. The size of the hash table is initialized in the linux-2.4.32 kernel based on size, which is useless in the linux2.6.10 kernel, and uses a red-black tree to manage all file descriptors instead of hashes.

2. Epoll_ctl function

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

This function is used to control events on a file descriptor, to register events, to modify events, and to delete events.

Parameter: EPFD: Epoll Private file descriptor generated by epoll_create;

OP: Operation type, with the following values:

Epoll_ctl_add Registration,

Epoll_ctl_mod Modify,

Epoll_ctl_del Delete

FD: The file descriptor to be controlled;

Event: Pointer to Epoll_event; If the call returns 0 successfully, the return is unsuccessful-1

The events field of the Epoll_event struct is an event of interest, with the following values:

Epollin: Indicates that the corresponding file descriptor can be read;

Epollout: Indicates that the corresponding file descriptor can be written;

Epollpri: Indicates that the corresponding file descriptor has an urgent data readable;

Epollerr: Indicates an error occurred in the corresponding file descriptor;

Epollhup: Indicates that the corresponding file descriptor is hung up;

Epollet: Indicates the corresponding file description have event occurred;

3. Event wait function

int epoll_wait (int epfd,struct epoll_event * events,intmaxevents,int timeout)

This function is used to poll for the occurrence of I/O events;

Parameters: EPFD: epoll-specific file descriptor generated by epoll_create;

Epoll_event: An array of events that are used for callback waiting processing;

Maxevents: The number of events that can be processed each time;

Timeout: Timeout value (ms) waiting for an I/O event, 1 never time out until an event occurs, 0 returns immediately

Main data structure:

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 */

};

In general, we use event variables to store event-corresponding file descriptors and event types when programming.

Instance Code

Server Segment Code

int Epollserver ()

{

int srvport = 6888;

Initsrvsocket (Srvport);

/* Create a Epoll handle and add the listener socket to the Epoll collection */

EPOLLFD = Epoll_create (max_events);

struct Epoll_event event;

event.events = Epollin | Epollet;

EVENT.DATA.FD = srvfd;

if (Epoll_ctl (EPOLLFD, Epoll_ctl_add, srvfd, &event) < 0)

{

printf ("Epoll Add failed:fd=%d\n", srvfd);

return-1;

}

printf ("Epollengine startup:port%d", srvport);

while (1)

{

/* Wait for event to occur */

int Nfds = epoll_wait (EPOLLFD, EventList, Max_events,-1);

if (Nfds = =-1)

{

printf ("epoll_wait");

Continue

}

/* Handle ALL Events */

int n = 0;

for (n < Nfds; n++)

Handleevent (EventList + N);

}

Close (EPOLLFD);

Close (SRVFD);

};

In Event handling handleevent (divided into Connection event processing and data receive send events)

void Handleevent (struct epoll_event* pevent)

{

if (pevent->data.fd = = srvfd)

{

Acceptconn (SRVFD);

}else{

RecvData (PEVENT->DATA.FD);

SendData (PEVENT->DATA.FD);

Epoll_ctl (EPOLLFD, Epoll_ctl_del, PEVENT->DATA.FD, pevent);

}

}

Read data from standard input, send to server side, server side returns as is, client receives and displays

void handle (int sockfd)

{

Char Sendline[maxline];

Char Recvline[maxline];

int n;

for (;;) {

if (Fgets (Sendline, MAXLINE, stdin) = = NULL)

Break

if (read (Stdin_fileno, sendline, MAXLINE) = = 0)

Break

n = Write (SOCKFD, Sendline, strlen (Sendline));

n = Read (SOCKFD, recvline, MAXLINE);

if (n = = 0) {

printf ("Echoclient:server terminatedprematurely\n");

Break

}

Write (Stdout_fileno, Recvline, N);

If the cache stream output with the standard library is sometimes problematic

Fputs (Recvline, stdout);

}

}

Run results (Linux under Trouble, directly copy console results)

Client:

[Email protected]:~$./echoclient

Welcome to Echoclient

123456

123456

Server-side:

[Email protected]:~/source/epollproject$./epoll

Epollengine Startup Port 6888

handleevent function, Handle:3, EVENT is 1

Accept Connection:5

handleevent function, Handle:5, EVENT is 1

RecvData function

SOCKET Handle:5: content:123456

Content is 123456

SendData function

senddata:123456

Note:

1. Here only the Epoll basic model is studied, in practice, in order to improve the monitoring efficiency of the Epoll model, it is generally only monitored in the monitoring thread, but the event is handled, but the event is delivered to other threads.

2. In order to improve the efficiency of event processing, we try to avoid threading when there is an event, processing the shutdown, typically creating a thread pool at system startup, and handling events with idle threads in the thread pool. In the event of the processing of the county will not be created, destroyed and other operations. Efficiency has also improved.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A brief analysis of Epoll communication model under Linux

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.