1. Introduction
Epoll is an asynchronous I/O notification method provided by Linux. Compared with the select mechanism, select is round-robin, while epoll is triggered, and the maximum number of select connections is only 1024, after this limit is exceeded, you can only use multi-process operations. Therefore, epoll is more efficient.
2. Main Functions
Epoll_create create epoll
Epoll_ctl Add a handle to epoll
Epoll_wait Wait until the epoll event is generated. If the registered handle changes, the epoll event is generated.
3. Main Process
/* Create epoll */iepollfd = epoll_create (myping_epollevent_max );
/* Set sicket options */
Stservaddr. uclen = sizeof (stservaddr); stservaddr. ucfamily = (uchar) af_lipc; stservaddr. usport = htons (lipc_global_port_myping); stservaddr. usaddr = htons (lipc_lip_addr_any);/* Create socket */ilipcfd = socket (pf_lipc, sock_dgram, lipc_proto_stcp );
/* Bind socket */iret + = BIND (ilipcfd, (struct sockaddr *) (& stservaddr), (uint) sizeof (lipc_sock_addr_s )); /* Listen socket */iret + = listen (ilipcfd, somaxconn);/* bind or listen Error */If (0! = Iret) {printf ("bind or listen socket failed \ r \ n"); (void) Close (ilipcfd); Return error_failed ;} /* regist socket to epoll */iret = myping_epollreg (epollin, ilipcfd, myping_lipclistencallback); If (0! = Iret) {printf ("regist lipc socket to epoll failed \ r \ n"); (void) Close (ilipcfd); Return error_failed ;}
/* Wait for event generation */
For (;) {/* This will be blocked until any registered event happend or timeout */infds = epoll_wait (g_iepollhandle, astepevt, myping_epollevent_max,-1 ); /* events generated by polling */for (I = 0; I <infds; I ++) {/* Get the registered callback function */pfcallback = (void *) (ulong) astepevt [I]. callback;/* call the relevant callback function for processing */pfcallback (astepevt [I]. events, astepevt [I]. data. FD );}}
4. Mechanism
In fact, a listener socket is registered on epoll first. When the socket listens to a data connection, a new socket is created to receive data, register the new socket handle to epoll, and then perform corresponding processing in the callback function of the socket.