Changes.old: Tweaks to 5.00 changelog
[man-pages.git] / man7 / epoll.7
blob40d9e5b37b5fed47dddc9255834d77133def3cd7
1 .\"  Copyright (C) 2003  Davide Libenzi
2 .\"
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.
8 .\"
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.
13 .\"
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/>.
17 .\" %%%LICENSE_END
18 .\"
19 .\"  Davide Libenzi <davidel@xmailserver.org>
20 .\"
21 .TH EPOLL 7 2019-03-06 "Linux" "Linux Programmer's Manual"
22 .SH NAME
23 epoll \- I/O event notification facility
24 .SH SYNOPSIS
25 .B #include <sys/epoll.h>
26 .SH DESCRIPTION
27 The
28 .B epoll
29 API performs a similar task to
30 .BR poll (2):
31 monitoring multiple file descriptors to see if I/O is possible on any of them.
32 The
33 .B epoll
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.
36 .PP
37 The central concept of the
38 .B epoll
39 API is the
40 .B epoll
41 .IR instance ,
42 an in-kernel data structure which, from a user-space perspective,
43 can be considered as a container for two lists:
44 .IP * 4
45 The
46 .I interest
47 list (sometimes also called the
48 .B epoll
49 set): the set of file descriptors that the process has registered
50 an interest in monitoring.
51 .IP *
52 The
53 .I ready
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.
59 .PP
60 The following system calls are provided to
61 create and manage an
62 .B epoll
63 instance:
64 .IP * 3
65 .BR epoll_create (2)
66 creates a new
67 .B epoll
68 instance and returns a file descriptor referring to that instance.
69 (The more recent
70 .BR epoll_create1 (2)
71 extends the functionality of
72 .BR epoll_create (2).)
73 .IP *
74 Interest in particular file descriptors is then registered via
75 .BR epoll_ctl (2),
76 which adds items to the interest list of the
77 .B epoll
78 instance.
79 .IP *
80 .BR epoll_wait (2)
81 waits for I/O events,
82 blocking the calling thread if no events are currently available.
83 (This system call can be thought of as fetching items from
84 the ready list of the
85 .B epoll
86 instance.)
87 .\"
88 .SS Level-triggered and edge-triggered
89 The
90 .B epoll
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.
95 Suppose that
96 this scenario happens:
97 .IP 1. 3
98 The file descriptor that represents the read side of a pipe
99 .RI ( rfd )
100 is registered on the
101 .B epoll
102 instance.
103 .IP 2.
104 A pipe writer writes 2\ kB of data on the write side of the pipe.
105 .IP 3.
106 A call to
107 .BR epoll_wait (2)
108 is done that will return
109 .I rfd
110 as a ready file descriptor.
111 .IP 4.
112 The pipe reader reads 1\ kB of data from
113 .IR rfd .
114 .IP 5.
115 A call to
116 .BR epoll_wait (2)
117 is done.
119 If the
120 .I rfd
121 file descriptor has been added to the
122 .B epoll
123 interface using the
124 .B EPOLLET
125 (edge-triggered)
126 flag, the call to
127 .BR epoll_wait (2)
128 done in step
129 .B 5
130 will probably hang despite the available data still present in the file
131 input buffer;
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.
136 So, in step
137 .B 5
138 the caller might end up waiting for some data that is already present inside
139 the input buffer.
140 In the above example, an event on
141 .I rfd
142 will be generated because of the write done in
143 .B 2
144 and the event is consumed in
145 .BR 3 .
146 Since the read operation done in
147 .B 4
148 does not consume the whole buffer data, the call to
149 .BR epoll_wait (2)
150 done in step
151 .B 5
152 might block indefinitely.
154 An application that employs the
155 .B EPOLLET
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
159 .B epoll
160 as an edge-triggered
161 .RB ( EPOLLET )
162 interface is as follows:
164 .TP 4
165 .B i
166 with nonblocking file descriptors; and
168 .B ii
169 by waiting for an event only after
170 .BR read (2)
172 .BR write (2)
173 return
174 .BR EAGAIN .
177 By contrast, when used as a level-triggered interface
178 (the default, when
179 .B EPOLLET
180 is not specified),
181 .B epoll
182 is simply a faster
183 .BR poll (2),
184 and can be used wherever the latter is used since it shares the
185 same semantics.
187 Since even with edge-triggered
188 .BR epoll ,
189 multiple events can be generated upon receipt of multiple chunks of data,
190 the caller has the option to specify the
191 .B EPOLLONESHOT
192 flag, to tell
193 .B epoll
194 to disable the associated file descriptor after the receipt of an event with
195 .BR epoll_wait (2).
196 When the
197 .B EPOLLONESHOT
198 flag is specified,
199 it is the caller's responsibility to rearm the file descriptor using
200 .BR epoll_ctl (2)
201 with
202 .BR EPOLL_CTL_MOD .
204 If multiple threads
205 (or processes, if child processes have inherited the
206 .B epoll
207 file descriptor across
208 .BR fork (2))
209 are blocked in
210 .BR epoll_wait (2)
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
213 .RB ( EPOLLET )
214 notification becomes ready,
215 just one of the threads (or processes) is awoken from
216 .BR epoll_wait (2).
217 This provides a useful optimization for avoiding "thundering herd" wake-ups
218 in some scenarios.
220 .SS Interaction with autosleep
221 If the system is in
222 .B autosleep
223 mode via
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
229 .BR epoll_ctl (2)
230 .B EPOLLWAKEUP
231 flag.
233 When the
234 .B EPOLLWAKEUP
235 flag is set in the
236 .B events
237 field for a
238 .IR "struct epoll_event" ,
239 the system will be kept awake from the moment the event is queued,
240 through the
241 .BR epoll_wait (2)
242 call which returns the event until the subsequent
243 .BR epoll_wait (2)
244 call.
245 If the event should keep the system awake beyond that time,
246 then a separate
247 .I wake_lock
248 should be taken before the second
249 .BR epoll_wait (2)
250 call.
251 .SS /proc interfaces
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
255 .\" .TP
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.
267 Currently,
268 .\" 2.6.29 (in 2.6.28, the default was 1/32 of lowmem)
269 the default value for
270 .I max_user_watches
271 is 1/25 (4%) of the available low memory,
272 divided by the registration cost in bytes.
273 .SS Example for suggested usage
274 While the usage of
275 .B epoll
276 when employed as a level-triggered interface does have the same
277 semantics as
278 .BR poll (2),
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
283 .BR listen (2)
284 has been called.
285 The function
286 .I do_use_fd()
287 uses the new ready file descriptor until
288 .B EAGAIN
289 is returned by either
290 .BR read (2)
292 .BR write (2).
293 An event-driven state machine application should, after having received
294 .BR EAGAIN ,
295 record its current state so that at the next call to
296 .I do_use_fd()
297 it will continue to
298 .BR read (2)
300 .BR write (2)
301 from where it stopped before.
303 .in +4n
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");
315     exit(EXIT_FAILURE);
318 ev.events = EPOLLIN;
319 ev.data.fd = listen_sock;
320 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == \-1) {
321     perror("epoll_ctl: listen_sock");
322     exit(EXIT_FAILURE);
325 for (;;) {
326     nfds = epoll_wait(epollfd, events, MAX_EVENTS, \-1);
327     if (nfds == \-1) {
328         perror("epoll_wait");
329         exit(EXIT_FAILURE);
330     }
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) {
337                 perror("accept");
338                 exit(EXIT_FAILURE);
339             }
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,
344                         &ev) == \-1) {
345                 perror("epoll_ctl: conn_sock");
346                 exit(EXIT_FAILURE);
347             }
348         } else {
349             do_use_fd(events[n].data.fd);
350         }
351     }
356 When used as an edge-triggered interface, for performance reasons, it is
357 possible to add the file descriptor inside the
358 .B epoll
359 interface
360 .RB ( EPOLL_CTL_ADD )
361 once by specifying
362 .RB ( EPOLLIN | EPOLLOUT ).
363 This allows you to avoid
364 continuously switching between
365 .B EPOLLIN
367 .B EPOLLOUT
368 calling
369 .BR epoll_ctl (2)
370 with
371 .BR EPOLL_CTL_MOD .
372 .SS Questions and answers
373 .IP 0. 4
374 What is the key used to distinguish the file descriptors registered in an
375 interest list?
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).
381 .IP 1.
382 What happens if you register the same file descriptor on an
383 .B epoll
384 instance twice?
386 You will probably get
387 .BR EEXIST .
388 However, it is possible to add a duplicate
389 .RB ( dup (2),
390 .BR dup2 (2),
391 .BR fcntl (2)
392 .BR F_DUPFD )
393 file descriptor to the same
394 .B epoll
395 instance.
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"
410 .\" mtk, Feb 2008
411 This can be a useful technique for filtering events,
412 if the duplicate file descriptors are registered with different
413 .I events
414 masks.
415 .IP 2.
416 Can two
417 .B epoll
418 instances wait for the same file descriptor?
419 If so, are events reported to both
420 .B epoll
421 file descriptors?
423 Yes, and events would be reported to both.
424 However, careful programming may be needed to do this correctly.
425 .IP 3.
426 Is the
427 .B epoll
428 file descriptor itself poll/epoll/selectable?
430 Yes.
431 If an
432 .B epoll
433 file descriptor has events waiting, then it will
434 indicate as being readable.
435 .IP 4.
436 What happens if one attempts to put an
437 .B epoll
438 file descriptor into its own file descriptor set?
441 .BR epoll_ctl (2)
442 call fails
443 .RB ( EINVAL ).
444 However, you can add an
445 .B epoll
446 file descriptor inside another
447 .B epoll
448 file descriptor set.
449 .IP 5.
450 Can I send an
451 .B epoll
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.
456 .IP 6.
457 Will closing a file descriptor cause it to be removed from all
458 .B epoll
459 interest lists?
461 Yes, but be aware of the following point.
462 A file descriptor is a reference to an open file description (see
463 .BR open (2)).
464 Whenever a file descriptor is duplicated via
465 .BR dup (2),
466 .BR dup2 (2),
467 .BR fcntl (2)
468 .BR F_DUPFD ,
470 .BR fork (2),
471 a new file descriptor referring to the same open file description is
472 created.
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
485 .BR epoll_ctl (2)
486 .BR EPOLL_CTL_DEL )
487 before it is duplicated.
488 Alternatively,
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
492 .BR dup (2)
494 .BR fork (2)).
495 .IP 7.
496 If more than one event occurs between
497 .BR epoll_wait (2)
498 calls, are they combined or reported separately?
500 They will be combined.
501 .IP 8.
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
507 this case.
508 Modify will reread available I/O.
509 .IP 9.
510 Do I need to continuously read/write a file descriptor
511 until
512 .B EAGAIN
513 when using the
514 .B EPOLLET
515 flag (edge-triggered behavior)?
517 Receiving an event from
518 .BR epoll_wait (2)
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)
522 read/write yields
523 .BR EAGAIN .
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
530 .BR EAGAIN .
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
535 descriptor.
536 For example, if you call
537 .BR read (2)
538 by asking to read a certain amount of data and
539 .BR read (2)
540 returns a lower number of bytes, you
541 can be sure of having exhausted the read I/O space for the file
542 descriptor.
543 The same is true when writing using
544 .BR write (2).
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
555 .BR epoll .)
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
561 all the ready files.
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
568 .BR epoll_wait (2),
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
573 .BR epoll_wait (2),
574 and in event #47 a condition causes event #13 to be closed.
575 If you remove the structure and
576 .BR close (2)
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
584 .BR close (2),
585 then mark its associated
586 data structure as removed and link it to a cleanup list.
587 If you find another
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.
591 .SH VERSIONS
593 .B epoll
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.
597 .SH CONFORMING TO
599 .B epoll
600 API is Linux-specific.
601 Some other systems provide similar
602 mechanisms, for example, FreeBSD has
603 .IR kqueue ,
604 and Solaris has
605 .IR /dev/poll .
606 .SH NOTES
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
611 directory.
613 .BR proc (5)
614 for further details.
617 .BR kcmp (2)
618 .B KCMP_EPOLL_TFD
619 operation can be used to test whether a file descriptor
620 is present in an epoll instance.
621 .SH SEE ALSO
622 .BR epoll_create (2),
623 .BR epoll_create1 (2),
624 .BR epoll_ctl (2),
625 .BR epoll_wait (2),
626 .BR poll (2),
627 .BR select (2)