All functions used by epoll are declared in the SYS/epoll. h header file. The following briefly describes the data structures and functions used:
Data Structure Used
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 */
};
The epoll_event struct is used to register events of interest and return events to be processed. The epoll_data consortium is used to save data related to a file descriptor that triggers the event. For example, a client is connected to the server, the server can obtain the socket file descriptor corresponding to the client by calling the accept function. This file descriptor can be assigned to the FD field of epoll_data so that subsequent read/write operations can be performed on this file descriptor. The events field of the epoll_event struct indicates the events of interest and the events triggered. The possible values are as follows: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 readable data (I don't quite understand what it means, it may be an event like closing the socket connection by the client );
Epollerr:Indicates that the corresponding file descriptor is incorrect;
Epollhup:Indicates that the corresponding file descriptor is hung up;
Epollet:Indicates that an event occurs in the corresponding file descriptor;
Functions used:
1. epoll_create Function
Function declaration:Int epoll_create (intSize)
This function generates a file descriptor dedicated to epoll, the parameter specifies the maximum range of the generated Descriptor (I think this parameter is similar to the first parameter of the select function, but I am not sure how to set it ).
2. epoll_ctl Function
Function declaration:Int epoll_ctl (intEpfd, IntOP, IntFD, Struct epoll_event *Event)
This function is used to control events on a file descriptor. You can register events, modify events, and delete events.
Parameter: epfd:Epoll_createThe generated epoll-specific file descriptor;
OP: the operation to be performed, such as registering an event. Possible valuesEpoll_ctl_addRegistration,Epoll_ctl_modRepair
Change,Epoll_ctl_delDelete
FD: the associated file descriptor;
Event: pointer to epoll_event;
If the call is successful, 0 is returned. If the call is unsuccessful,-1 is returned.
3. epoll_wait Function
Function declaration:Int epoll_wait (intEpfd,Struct epoll_event *Events,IntMaxevents,IntTimeout)
This function is used to poll the occurrence of I/O events;
Parameters:
Epfd:Epoll_createThe generated epoll-specific file descriptor;
Epoll_event: the array used to return the events to be processed;
Maxevents: Number of events that can be processed each time;
Timeout: the timeout value for waiting for an I/O event;
Number of events returned.
Example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <sys/socket. h>
# Include <sys/Wait. H>
# Include <unistd. h>
# Include <ARPA/inet. h>
# Include <OpenSSL/SSL. h>
# Include <OpenSSL/err. h>
# Include <fcntl. h>
# Include <sys/epoll. h>
# Include <sys/time. h>
# Include <sys/resource. h>
# Define maxbuckets 1024
# Define maxepollsize 10000
/*
Setnonblocking-set the handle as a non-blocking method
*/
Int setnonblocking (INT sockfd)
{
If (fcntl (sockfd, f_setfl, fcntl (sockfd, f_getfd, 0) | o_nonblock) =-1 ){
Return-1;
}
Return 0;
}
/*
Handle_message-process messages sent and received on each socket
*/
Int handle_message (INT new_fd)
{
Char Buf [maxbuf + 1];
Int Len;
/* Start to process the data sending and receiving of each new connection */
Bzero (BUF, maxbuf + 1 );
/* Receive client messages */
Len = Recv (new_fd, Buf, maxbuf, 0 );
If (LEN> 0)
Printf
("% D received the message successfully: '% s', % d bytes of data/N ",
New_fd, Buf, Len );
Else {
If (LEN <0)
Printf
("Message receiving failed! Error code: % d, error message: '% s'/N ",
Errno, strerror (errno ));
Close (new_fd );
Return-1;
}
/* Process the data sent and received by each new connection */
Return Len;
}
************************ ********************
* Filename: epoll-server.c
* Purpose: demonstrate how epoll processes massive socket connections
* Wrote by: zhoulifa (zhoulifa@163.com) Zhou Lifa (http://zhoulifa.bokee.com)
Linux enthusiasts Linux knowledge disseminators sohowhose developers are best at C Language
* Date Time:
* Note: Anyone can copy the code and use these documents, including your commercial use.
* But follow the GPL
* Thanks to: Google
* Hope: more and more people are expected to contribute to the development of science and technology.
* Technology stands on the shoulders of giants and makes progress faster! Thank you for your contributions to the open source team!
**************************************** *****************************/
Int main (INT argc, char ** argv)
{
Int listener, new_fd, kdpfd, NFDs, N, RET, curfds;
Socklen_t Len;
Struct sockaddr_in my_addr, their_addr;
Unsigned int myport, lisnum;
Struct epoll_event EV;
Struct epoll_event events [maxepollsize];
Struct rlimit RT;
If (argv [1])
Myport = atoi (argv [1]);
Else
Myport = 7838;
If (argv [2])
Lisnum = atoi (argv [2]);
Else
Lisnum = 2;
/* Set the maximum number of files that each process can open */
Rt. rlim_max = Rt. rlim_cur = maxepollsize;
If (setrlimit (rlimit_nofile, & RT) =-1 ){
Perror ("setrlimit ");
Exit (1 );
}
Else printf ("system resource parameter set! /N ");
/* Enable socket listening */
If (listener = socket (pf_inet, sock_stream, 0) =-1 ){
Perror ("socket ");
Exit (1 );
} Else
Printf ("socket created successfully! /N ");
Setnonblocking (listener );
Bzero (& my_addr, sizeof (my_addr ));
My_addr.sin_family = pf_inet;
My_addr.sin_port = htons (myport );
If (argv [3])
My_addr.sin_addr.s_addr = inet_addr (argv [3]);
Else
My_addr.sin_addr.s_addr = inaddr_any;
If (bind
(Listener, (struct sockaddr *) & my_addr, sizeof (struct sockaddr ))
=-1 ){
Perror ("bind ");
Exit (1 );
} Else
Printf ("IP address and port bound successfully/N ");
If (Listen (listener, lisnum) =-1 ){
Perror ("listen ");
Exit (1 );
} Else
Printf ("service enabled successfully! /N ");
/* Create an epoll handle and add the listening socket to the epoll Set */
Kdpfd = epoll_create (maxepollsize );
Len = sizeof (struct sockaddr_in );
Ev. Events = epollin | epollet;
Ev. Data. FD = listener;
If (epoll_ctl (kdpfd, epoll_ctl_add, listener, & eV) <0 ){
Fprintf (stderr, "epoll set insertion error: FD = % d/N", listener );
Return-1;
} Else
Printf ("listening socket added to epoll successful! /N ");
Curfds = 1;
While (1 ){
/* Wait for an event to occur */
NFDs = epoll_wait (kdpfd, events, curfds,-1 );
If (NFDs =-1 ){
Perror ("epoll_wait ");
Break;
}
/* Process all events */
For (n = 0; n <NFDs; ++ N ){
If (events [N]. Data. FD = listener ){
New_fd = accept (listener, (struct sockaddr *) & their_addr,
& Len );
If (new_fd <0 ){
Perror ("accept ");
Continue;
} Else
Printf ("connected from: % d, allocated socket: % d/N", inet_ntoa (their_addr.sin_addr), ntohs (their_addr.sin_port), new_fd );
Setnonblocking (new_fd );
Ev. Events = epollin | epollet;
Ev. Data. FD = new_fd;
If (epoll_ctl (kdpfd, epoll_ctl_add, new_fd, & eV) <0 ){
Fprintf (stderr, "failed to add socket '% d' to epoll! % S/n ",
New_fd, strerror (errno ));
Return-1;
}
Curfds ++;
} Else {
Ret = handle_message (events [N]. Data. FD );
If (Ret <1 & errno! = 11 ){
Epoll_ctl (kdpfd, epoll_ctl_del, events [N]. Data. FD,
& EV );
Curfds --;
}
}
}
}
Close (listener );
Return 0;
}
Run the following command to compile the program:
Gcc-wall epoll-server.c-O Server
You must have the administrator privilege to run this program!
Sudo./Server 7838 1
By testing this server, it may process 10000-3 = 9997 connections at the same time!
If this is an online service system, it can support 9997 concurrent online users, such as games and chats.