1 .\" Copyright (C) 2003 Davide Libenzi
3 .\" %%%LICENSE_START(GPLv2+_SW_3_PARA)
4 .\" This program is free software; you can redistribute it and/or modify
5 .\" it under the terms of the GNU General Public License as published by
6 .\" the Free Software Foundation; either version 2 of the License, or
7 .\" (at your option) any later version.
9 .\" This program is distributed in the hope that it will be useful,
10 .\" but WITHOUT ANY WARRANTY; without even the implied warranty of
11 .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 .\" GNU General Public License for more details.
14 .\" You should have received a copy of the GNU General Public
15 .\" License along with this manual; if not, see
16 .\" <http://www.gnu.org/licenses/>.
19 .\" Davide Libenzi <davidel@xmailserver.org>
21 .TH EPOLL 7 2019-03-06 "Linux" "Linux Programmer's Manual"
23 epoll \- I/O event notification facility
25 .B #include <sys/epoll.h>
29 API performs a similar task to
31 monitoring multiple file descriptors to see if I/O is possible on any of them.
34 API can be used either as an edge-triggered or a level-triggered
35 interface and scales well to large numbers of watched file descriptors.
37 The central concept of the
42 an in-kernel data structure which, from a user-space perspective,
43 can be considered as a container for two lists:
47 list (sometimes also called the
49 set): the set of file descriptors that the process has registered
50 an interest in monitoring.
54 list: the set of file descriptors that are "ready" for I/O.
55 The ready list is a subset of
56 (or, more precisely, a set of references to)
57 the file descriptors in the interest list that is dynamically populated
58 by the kernel as a result of I/O activity on those file descriptors.
60 The following system calls are provided to
68 instance and returns a file descriptor referring to that instance.
71 extends the functionality of
72 .BR epoll_create (2).)
74 Interest in particular file descriptors is then registered via
76 which adds items to the interest list of the
82 blocking the calling thread if no events are currently available.
83 (This system call can be thought of as fetching items from
88 .SS Level-triggered and edge-triggered
91 event distribution interface is able to behave both as edge-triggered
92 (ET) and as level-triggered (LT).
93 The difference between the two mechanisms
94 can be described as follows.
96 this scenario happens:
98 The file descriptor that represents the read side of a pipe
104 A pipe writer writes 2\ kB of data on the write side of the pipe.
108 is done that will return
110 as a ready file descriptor.
112 The pipe reader reads 1\ kB of data from
121 file descriptor has been added to the
130 will probably hang despite the available data still present in the file
132 meanwhile the remote peer might be expecting a response based on the
133 data it already sent.
134 The reason for this is that edge-triggered mode
135 delivers events only when changes occur on the monitored file descriptor.
138 the caller might end up waiting for some data that is already present inside
140 In the above example, an event on
142 will be generated because of the write done in
144 and the event is consumed in
146 Since the read operation done in
148 does not consume the whole buffer data, the call to
152 might block indefinitely.
154 An application that employs the
156 flag should use nonblocking file descriptors to avoid having a blocking
157 read or write starve a task that is handling multiple file descriptors.
158 The suggested way to use
162 interface is as follows:
166 with nonblocking file descriptors; and
169 by waiting for an event only after
177 By contrast, when used as a level-triggered interface
184 and can be used wherever the latter is used since it shares the
187 Since even with edge-triggered
189 multiple events can be generated upon receipt of multiple chunks of data,
190 the caller has the option to specify the
194 to disable the associated file descriptor after the receipt of an event with
199 it is the caller's responsibility to rearm the file descriptor using
205 (or processes, if child processes have inherited the
207 file descriptor across
211 waiting on the same the same epoll file descriptor and a file descriptor
212 in the interest list that is marked for edge-triggered
214 notification becomes ready,
215 just one of the threads (or processes) is awoken from
217 This provides a useful optimization for avoiding "thundering herd" wake-ups
220 .SS Interaction with autosleep
224 .I /sys/power/autosleep
225 and an event happens which wakes the device from sleep, the device
226 driver will keep the device awake only until that event is queued.
227 To keep the device awake until the event has been processed,
228 it is necessary to use the
238 .IR "struct epoll_event" ,
239 the system will be kept awake from the moment the event is queued,
242 call which returns the event until the subsequent
245 If the event should keep the system awake beyond that time,
248 should be taken before the second
252 The following interfaces can be used to limit the amount of
253 kernel memory consumed by epoll:
254 .\" Following was added in 2.6.28, but them removed in 2.6.29
256 .\" .IR /proc/sys/fs/epoll/max_user_instances " (since Linux 2.6.28)"
257 .\" This specifies an upper limit on the number of epoll instances
258 .\" that can be created per real user ID.
260 .IR /proc/sys/fs/epoll/max_user_watches " (since Linux 2.6.28)"
261 This specifies a limit on the total number of
262 file descriptors that a user can register across
263 all epoll instances on the system.
264 The limit is per real user ID.
265 Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel,
266 and roughly 160 bytes on a 64-bit kernel.
268 .\" 2.6.29 (in 2.6.28, the default was 1/32 of lowmem)
269 the default value for
271 is 1/25 (4%) of the available low memory,
272 divided by the registration cost in bytes.
273 .SS Example for suggested usage
276 when employed as a level-triggered interface does have the same
279 the edge-triggered usage requires more clarification to avoid stalls
280 in the application event loop.
281 In this example, listener is a
282 nonblocking socket on which
287 uses the new ready file descriptor until
289 is returned by either
293 An event-driven state machine application should, after having received
295 record its current state so that at the next call to
301 from where it stopped before.
305 #define MAX_EVENTS 10
306 struct epoll_event ev, events[MAX_EVENTS];
307 int listen_sock, conn_sock, nfds, epollfd;
309 /* Code to set up listening socket, \(aqlisten_sock\(aq,
310 (socket(), bind(), listen()) omitted */
312 epollfd = epoll_create1(0);
313 if (epollfd == \-1) {
314 perror("epoll_create1");
319 ev.data.fd = listen_sock;
320 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == \-1) {
321 perror("epoll_ctl: listen_sock");
326 nfds = epoll_wait(epollfd, events, MAX_EVENTS, \-1);
328 perror("epoll_wait");
332 for (n = 0; n < nfds; ++n) {
333 if (events[n].data.fd == listen_sock) {
334 conn_sock = accept(listen_sock,
335 (struct sockaddr *) &addr, &addrlen);
336 if (conn_sock == \-1) {
340 setnonblocking(conn_sock);
341 ev.events = EPOLLIN | EPOLLET;
342 ev.data.fd = conn_sock;
343 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock,
345 perror("epoll_ctl: conn_sock");
349 do_use_fd(events[n].data.fd);
356 When used as an edge-triggered interface, for performance reasons, it is
357 possible to add the file descriptor inside the
360 .RB ( EPOLL_CTL_ADD )
362 .RB ( EPOLLIN | EPOLLOUT ).
363 This allows you to avoid
364 continuously switching between
372 .SS Questions and answers
374 What is the key used to distinguish the file descriptors registered in an
377 The key is the combination of the file descriptor number and
378 the open file description
379 (also known as an "open file handle",
380 the kernel's internal representation of an open file).
382 What happens if you register the same file descriptor on an
386 You will probably get
388 However, it is possible to add a duplicate
393 file descriptor to the same
396 .\" But a file descriptor duplicated by fork(2) can't be added to the
397 .\" set, because the [file *, fd] pair is already in the epoll set.
398 .\" That is a somewhat ugly inconsistency. On the one hand, a child process
399 .\" cannot add the duplicate file descriptor to the epoll set. (In every
400 .\" other case that I can think of, file descriptors duplicated by fork have
401 .\" similar semantics to file descriptors duplicated by dup() and friends.) On
402 .\" the other hand, the very fact that the child has a duplicate of the
403 .\" file descriptor means that even if the parent closes its file descriptor,
404 .\" then epoll_wait() in the parent will continue to receive notifications for
405 .\" that file descriptor because of the duplicated file descriptor in the child.
407 .\" See http://thread.gmane.org/gmane.linux.kernel/596462/
408 .\" "epoll design problems with common fork/exec patterns"
411 This can be a useful technique for filtering events,
412 if the duplicate file descriptors are registered with different
418 instances wait for the same file descriptor?
419 If so, are events reported to both
423 Yes, and events would be reported to both.
424 However, careful programming may be needed to do this correctly.
428 file descriptor itself poll/epoll/selectable?
433 file descriptor has events waiting, then it will
434 indicate as being readable.
436 What happens if one attempts to put an
438 file descriptor into its own file descriptor set?
444 However, you can add an
446 file descriptor inside another
452 file descriptor over a UNIX domain socket to another process?
454 Yes, but it does not make sense to do this, since the receiving process
455 would not have copies of the file descriptors in the interest list.
457 Will closing a file descriptor cause it to be removed from all
461 Yes, but be aware of the following point.
462 A file descriptor is a reference to an open file description (see
464 Whenever a file descriptor is duplicated via
471 a new file descriptor referring to the same open file description is
473 An open file description continues to exist until all
474 file descriptors referring to it have been closed.
476 A file descriptor is removed from an
477 interest list only after all the file descriptors referring to the underlying
478 open file description have been closed.
479 This means that even after a file descriptor that is part of an
480 interest list has been closed,
481 events may be reported for that file descriptor if other file
482 descriptors referring to the same underlying file description remain open.
483 To prevent this happening,
484 the file descriptor must be explicitly removed from the interest list (using
487 before it is duplicated.
489 the application must ensure that all file descriptors are closed
490 (which may be difficult if file descriptors were duplicated
491 behind the scenes by library functions that used
496 If more than one event occurs between
498 calls, are they combined or reported separately?
500 They will be combined.
502 Does an operation on a file descriptor affect the
503 already collected but not yet reported events?
505 You can do two operations on an existing file descriptor.
506 Remove would be meaningless for
508 Modify will reread available I/O.
510 Do I need to continuously read/write a file descriptor
515 flag (edge-triggered behavior)?
517 Receiving an event from
519 should suggest to you that such
520 file descriptor is ready for the requested I/O operation.
521 You must consider it ready until the next (nonblocking)
524 When and how you will use the file descriptor is entirely up to you.
526 For packet/token-oriented files (e.g., datagram socket,
527 terminal in canonical mode),
528 the only way to detect the end of the read/write I/O space
529 is to continue to read/write until
532 For stream-oriented files (e.g., pipe, FIFO, stream socket), the
533 condition that the read/write I/O space is exhausted can also be detected by
534 checking the amount of data read from / written to the target file
536 For example, if you call
538 by asking to read a certain amount of data and
540 returns a lower number of bytes, you
541 can be sure of having exhausted the read I/O space for the file
543 The same is true when writing using
545 (Avoid this latter technique if you cannot guarantee that
546 the monitored file descriptor always refers to a stream-oriented file.)
547 .SS Possible pitfalls and ways to avoid them
549 .B o Starvation (edge-triggered)
551 If there is a large amount of I/O space,
552 it is possible that by trying to drain
553 it the other files will not get processed causing starvation.
554 (This problem is not specific to
557 The solution is to maintain a ready list
558 and mark the file descriptor as ready
559 in its associated data structure, thereby allowing the application to
560 remember which files need to be processed but still round robin amongst
562 This also supports ignoring subsequent events you
563 receive for file descriptors that are already ready.
565 .B o If using an event cache...
567 If you use an event cache or store all the file descriptors returned from
569 then make sure to provide a way to mark
570 its closure dynamically (i.e., caused by
571 a previous event's processing).
572 Suppose you receive 100 events from
574 and in event #47 a condition causes event #13 to be closed.
575 If you remove the structure and
577 the file descriptor for event #13, then your
578 event cache might still say there are events waiting for that
579 file descriptor causing confusion.
581 One solution for this is to call, during the processing of event 47,
582 .BR epoll_ctl ( EPOLL_CTL_DEL )
583 to delete file descriptor 13 and
585 then mark its associated
586 data structure as removed and link it to a cleanup list.
588 event for file descriptor 13 in your batch processing,
589 you will discover the file descriptor had been
590 previously removed and there will be no confusion.
594 API was introduced in Linux kernel 2.5.44.
595 .\" Its interface should be finalized in Linux kernel 2.5.66.
596 Support was added to glibc in version 2.3.2.
600 API is Linux-specific.
601 Some other systems provide similar
602 mechanisms, for example, FreeBSD has
607 The set of file descriptors that is being monitored via
608 an epoll file descriptor can be viewed via the entry for
609 the epoll file descriptor in the process's
610 .IR /proc/[pid]/fdinfo
619 operation can be used to test whether a file descriptor
620 is present in an epoll instance.
622 .BR epoll_create (2),
623 .BR epoll_create1 (2),