select

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
Copy the code
  • selectThe file descriptors monitored by functions fall into three categories, respectivelywritefds,readfds, andexceptfds. The select function blocks until a descriptor is ready (data readable, writable, or except), or a timeout (timeout specifies the wait time), and the function returns.
  • whenselectThe function returns by traversingfdset, to find the ready oneFile descriptor
  • selectCurrently supported on almost all platforms, its good cross-platform support is one of its advantages
  • selectThe disadvantage is that a single process can monitorFile descriptorThere is a maximum limit to the number of bytes, typically 1024 on Linux

poll

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

Copy the code

Unlike select, which uses three bitmaps to represent three FDSets, poll uses a pointer to a PollFD

struct pollfd {
    int   fd;         /* file descriptor */
    short events;     /* requested events */
    short revents;    /* returned events */
};
Copy the code
  • pollfdThe structure contains the events to monitor and the events that occur
  • pollfdThere is no maximum number limit (but too many can degrade performance)
  • andselectThe function is the same,pollAfter you return, you need to pollpollfdTo get readyFile descriptor

Select and poll both need to loop through the file descriptor to get the socket ready on return. In fact, a large number of clients connected at the same time may have very few ready at any one time, so the efficiency decreases linearly as the number of monitored descriptors increases

epoll

int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
Copy the code
  • inselect/pollIn, the kernel scans all monitored file descriptors only after a process calls certain methods
  • epollIn advance byepoll_ctl()Once a file descriptor is in place, the kernel uses a callback mechanism similar to callback to quickly activate the file descriptor when the process callsepoll_wait()Will be notified
  • The traversal of file descriptors has been removed, instead listening for callbacks
  • epollThe advantages of
    1. There is no limit to the number of descriptors monitored. The maximum number of FDS it can support is the maximum number of files that can be opened. This number is generally much higher than 2048, for example, around 100,000 on a 1GB machine
    2. The efficiency of IO does not decrease as the number of FDS monitored increases.epollDifferent from theselectandpollPolling is implemented through the callback function defined by each FD. Only ready FDS execute callback functions

reference

Linux IO mode and select, poll, epoll details