EPoll communication model in Linux

Source: Internet
Author: User
EPoll communication model in Linux brief introduction to EPoll communication model: EPoll is based on the I/O event notification mechanism, and the system notifies users that the SOCKET triggers the relevant I/O events, the event contains the corresponding file descriptor and event type, so that the application can target the event and the sour of the event...
EPoll communication model in Linux brief introduction to EPoll communication model: EPoll is based on the I/O event notification mechanism, and the system notifies users that the SOCKET triggers the relevant I/O events, the event contains the corresponding file descriptor and event type, so that the application can handle the event and the event source (Acception, Read, Write, Error ). Compared with the original SELECT model (the user actively checks the SOCKET in turn), it becomes a passive waiting system to inform the active SOCKET, which improves the performance a lot (no need to traverse all the sockets in turn, instead, it only processes active SOCKET events ). Basic steps for www.2cto.com:
It is good at handling a large number of concurrent user requests in a timely manner to complete data interaction between the server and the client. A simple implementation procedure is as follows: (1) create a listening socket: ListenSock and set this descriptor to non-blocking mode. call the Listen () function to Listen for connection requests on this socket. (2) use the epoll_create () function to create a file description and set the maximum number of socket descriptors that can be managed. (3) register ListenSock into EPoll for monitoring (4) Start EPoll monitoring. epoll_wait () waits for the epoll event to occur. (5) If the epoll event indicates a new connection request, call the accept () function and add the new connection to EPoll. If it is read/write or an error is reported, call the corresponding Handle for processing. (6) continue monitoring until it is stopped. Communication subject framework:
Note: the appeal process is just a simple linear instance. in actual application, in order to improve the monitoring efficiency, EPOLL is often used to handle events that are monitored by other specialized task threads, to improve the efficiency of EPoll monitoring. This function is mainly used to create an int epoll_create (int size) for API1.EPoll. this function generates an epoll file descriptor. the parameter specifies the maximum range of the generated descriptor. The size of the hash table is initialized in the linux-2.4.32 kernel based on the size. in the Linux Kernel 2.6.10, this parameter is useless and uses the red/black tree to manage all file descriptors instead of hash. Www.2cto.com 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. you can register events and modify events, delete events. Parameter: epfd: epoll-specific file descriptor generated by epoll_create; op: Operation type, with the following values: EPOLL_CTL_ADD registration, EPOLL_CTL_MOD modification, EPOLL_CTL_DEL deletion fd: file descriptor to be controlled; event: the pointer to epoll_event. if the call succeeds, 0 is returned. if the call fails, the-1epoll_event struct's events field is returned, which indicates an event of interest. The value is EPOLLIN, which 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 urgent data readable; EPOLLERR: indicates that the corresponding file descriptor has an error; EPOLLHUP: indicates that the corresponding file descriptor is hung up; EPOLLET: indicates that the corresponding file descriptor has an event; 3. event wait function int epoll_wait (int epfd, struct epoll_event * Events, int maxevents, int timeout) this function is used to poll the occurrence of I/O events. parameter: epfd: epoll-specific file descriptor generated by epoll_create; epoll_event: array of events to be processed; maxevents: number of events that can be processed each time; timeout: timeout value for I/O events (MS);-1 Never times out, triggered only when an event occurs. 0 immediately returns the primary 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 */}; ww When programming, we use event variables to store file descriptors and event types corresponding to events. Instance code server segment code int EPollServer () {int srvPort = 6888; initSrvSocket (srvPort);/* create an epoll handle, add the listening 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 occurrence */int nfds = epoll_wait (epollfd, eventList, MAX_EVENTS,-1); if (nfds =-1) {printf ("epoll_wait"); continue;}/* process all events */int n = 0; (; n <nfds; n ++) handleEvent (eventList + n) ;}close (epollfd); close (srvfd );}; void handleEvent (struct epoll_event * pEvent) {if (pEvent-> data. fd = srvfd) {www.2cto.com AcceptConn (srvfd);} else {RecvData (pEvent-> data. fd); SendData (pEvent-> data. fd); epoll_ctl (epollfd, EPOLL_CTL_DEL, pEvent-> data. fd, pEvent) ;}}// read data from the standard input and send it to the server. the server returns the data as is, and the client receives the data and displays the 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) {www.2cto.com printf ("echoclient: server terminated prematurely \ n"); break;} write (STDOUT_FILENO, recvline, n );
// If the cache stream output of the standard library is used, the problem may occur sometimes. // fputs (recvline, stdout) ;}} running result (in Linux, copy the console result directly)
Client: administrator @ ubuntu :~ $./Echoclient welcome to echoclient123456123456 server: administrator @ ubuntu :~ /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 www.2cto.com socket handle: 5: CONTENT: 123456 content is 123456 SendData functionSendData: 123456 note: 1. here, we only learned the basic EPoll model. in practical applications, to improve the monitoring efficiency of the EPoll model, we generally only perform monitoring in the monitoring thread, but only process the event, instead, the event is delivered to other threads for processing.
2. to improve the efficiency of event processing, we try to avoid opening up thread processing when there is an event and closing the processing. generally, a thread pool will be created when the system starts, submit the event to the idle thread in the thread pool for processing. No county creation or destruction operations are performed during event handling. The efficiency is also improved. The complete code has been uploaded to: http://www.oschina.net/code/snippet_100374_11184includes the client, and the server author is xikunlun.
Related Article

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.