OSDN Git Service

LDP: Update original to LDP v3.67
[linuxjm/LDP_man-pages.git] / original / man7 / epoll.7
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 2012-04-17 "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 The following system calls are provided to
37 create and manage an
38 .B epoll
39 instance:
40 .IP * 3
41 .BR epoll_create (2)
42 creates an
43 .B epoll
44 instance and returns a file descriptor referring to that instance.
45 (The more recent
46 .BR epoll_create1 (2)
47 extends the functionality of
48 .BR epoll_create (2).)
49 .IP *
50 Interest in particular file descriptors is then registered via
51 .BR epoll_ctl (2).
52 The set of file descriptors currently registered on an
53 .B epoll
54 instance is sometimes called an
55 .I epoll
56 set.
57 .IP *
58 .BR epoll_wait (2)
59 waits for I/O events,
60 blocking the calling thread if no events are currently available.
61 .SS Level-triggered and edge-triggered
62 The
63 .B epoll
64 event distribution interface is able to behave both as edge-triggered
65 (ET) and as level-triggered (LT).
66 The difference between the two mechanisms
67 can be described as follows.
68 Suppose that
69 this scenario happens:
70 .IP 1. 3
71 The file descriptor that represents the read side of a pipe
72 .RI ( rfd )
73 is registered on the
74 .B epoll
75 instance.
76 .IP 2.
77 A pipe writer writes 2 kB of data on the write side of the pipe.
78 .IP 3.
79 A call to
80 .BR epoll_wait (2)
81 is done that will return
82 .I rfd
83 as a ready file descriptor.
84 .IP 4.
85 The pipe reader reads 1 kB of data from
86 .IR rfd .
87 .IP 5.
88 A call to
89 .BR epoll_wait (2)
90 is done.
91 .PP
92 If the
93 .I rfd
94 file descriptor has been added to the
95 .B epoll
96 interface using the
97 .B EPOLLET
98 (edge-triggered)
99 flag, the call to
100 .BR epoll_wait (2)
101 done in step
102 .B 5
103 will probably hang despite the available data still present in the file
104 input buffer;
105 meanwhile the remote peer might be expecting a response based on the
106 data it already sent.
107 The reason for this is that edge-triggered mode
108 delivers events only when changes occur on the monitored file descriptor.
109 So, in step
110 .B 5
111 the caller might end up waiting for some data that is already present inside
112 the input buffer.
113 In the above example, an event on
114 .I rfd
115 will be generated because of the write done in
116 .B 2
117 and the event is consumed in
118 .BR 3 .
119 Since the read operation done in
120 .B 4
121 does not consume the whole buffer data, the call to
122 .BR epoll_wait (2)
123 done in step
124 .B 5
125 might block indefinitely.
126
127 An application that employs the
128 .B EPOLLET
129 flag should use nonblocking file descriptors to avoid having a blocking
130 read or write starve a task that is handling multiple file descriptors.
131 The suggested way to use
132 .B epoll
133 as an edge-triggered
134 .RB ( EPOLLET )
135 interface is as follows:
136 .RS
137 .TP 4
138 .B i
139 with nonblocking file descriptors; and
140 .TP
141 .B ii
142 by waiting for an event only after
143 .BR read (2)
144 or
145 .BR write (2)
146 return
147 .BR EAGAIN .
148 .RE
149 .PP
150 By contrast, when used as a level-triggered interface
151 (the default, when
152 .B EPOLLET
153 is not specified),
154 .B epoll
155 is simply a faster
156 .BR poll (2),
157 and can be used wherever the latter is used since it shares the
158 same semantics.
159
160 Since even with edge-triggered
161 .BR epoll ,
162 multiple events can be generated upon receipt of multiple chunks of data,
163 the caller has the option to specify the
164 .B EPOLLONESHOT
165 flag, to tell
166 .B epoll
167 to disable the associated file descriptor after the receipt of an event with
168 .BR epoll_wait (2).
169 When the
170 .B EPOLLONESHOT
171 flag is specified,
172 it is the caller's responsibility to rearm the file descriptor using
173 .BR epoll_ctl (2)
174 with
175 .BR EPOLL_CTL_MOD .
176 .SS /proc interfaces
177 The following interfaces can be used to limit the amount of
178 kernel memory consumed by epoll:
179 .\" Following was added in 2.6.28, but them removed in 2.6.29
180 .\" .TP
181 .\" .IR /proc/sys/fs/epoll/max_user_instances " (since Linux 2.6.28)"
182 .\" This specifies an upper limit on the number of epoll instances
183 .\" that can be created per real user ID.
184 .TP
185 .IR /proc/sys/fs/epoll/max_user_watches " (since Linux 2.6.28)"
186 This specifies a limit on the total number of
187 file descriptors that a user can register across
188 all epoll instances on the system.
189 The limit is per real user ID.
190 Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel,
191 and roughly 160 bytes on a 64-bit kernel.
192 Currently,
193 .\" 2.6.29 (in 2.6.28, the default was 1/32 of lowmem)
194 the default value for
195 .I max_user_watches
196 is 1/25 (4%) of the available low memory,
197 divided by the registration cost in bytes.
198 .SS Example for suggested usage
199 While the usage of
200 .B epoll
201 when employed as a level-triggered interface does have the same
202 semantics as
203 .BR poll (2),
204 the edge-triggered usage requires more clarification to avoid stalls
205 in the application event loop.
206 In this example, listener is a
207 nonblocking socket on which
208 .BR listen (2)
209 has been called.
210 The function
211 .I do_use_fd()
212 uses the new ready file descriptor until
213 .B EAGAIN
214 is returned by either
215 .BR read (2)
216 or
217 .BR write (2).
218 An event-driven state machine application should, after having received
219 .BR EAGAIN ,
220 record its current state so that at the next call to
221 .I do_use_fd()
222 it will continue to
223 .BR read (2)
224 or
225 .BR write (2)
226 from where it stopped before.
227
228 .in +4n
229 .nf
230 #define MAX_EVENTS 10
231 struct epoll_event ev, events[MAX_EVENTS];
232 int listen_sock, conn_sock, nfds, epollfd;
233
234 /* Set up listening socket, \(aqlisten_sock\(aq (socket(),
235    bind(), listen()) */
236
237 epollfd = epoll_create(10);
238 if (epollfd == \-1) {
239     perror("epoll_create");
240     exit(EXIT_FAILURE);
241 }
242
243 ev.events = EPOLLIN;
244 ev.data.fd = listen_sock;
245 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == \-1) {
246     perror("epoll_ctl: listen_sock");
247     exit(EXIT_FAILURE);
248 }
249
250 for (;;) {
251     nfds = epoll_wait(epollfd, events, MAX_EVENTS, \-1);
252     if (nfds == \-1) {
253         perror("epoll_pwait");
254         exit(EXIT_FAILURE);
255     }
256
257     for (n = 0; n < nfds; ++n) {
258         if (events[n].data.fd == listen_sock) {
259             conn_sock = accept(listen_sock,
260                             (struct sockaddr *) &local, &addrlen);
261             if (conn_sock == \-1) {
262                 perror("accept");
263                 exit(EXIT_FAILURE);
264             }
265             setnonblocking(conn_sock);
266             ev.events = EPOLLIN | EPOLLET;
267             ev.data.fd = conn_sock;
268             if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock,
269                         &ev) == \-1) {
270                 perror("epoll_ctl: conn_sock");
271                 exit(EXIT_FAILURE);
272             }
273         } else {
274             do_use_fd(events[n].data.fd);
275         }
276     }
277 }
278 .fi
279 .in
280
281 When used as an edge-triggered interface, for performance reasons, it is
282 possible to add the file descriptor inside the
283 .B epoll
284 interface
285 .RB ( EPOLL_CTL_ADD )
286 once by specifying
287 .RB ( EPOLLIN | EPOLLOUT ).
288 This allows you to avoid
289 continuously switching between
290 .B EPOLLIN
291 and
292 .B EPOLLOUT
293 calling
294 .BR epoll_ctl (2)
295 with
296 .BR EPOLL_CTL_MOD .
297 .SS Questions and answers
298 .TP 4
299 .B Q0
300 What is the key used to distinguish the file descriptors registered in an
301 .B epoll
302 set?
303 .TP
304 .B A0
305 The key is the combination of the file descriptor number and
306 the open file description
307 (also known as an "open file handle",
308 the kernel's internal representation of an open file).
309 .TP
310 .B Q1
311 What happens if you register the same file descriptor on an
312 .B epoll
313 instance twice?
314 .TP
315 .B A1
316 You will probably get
317 .BR EEXIST .
318 However, it is possible to add a duplicate
319 .RB ( dup (2),
320 .BR dup2 (2),
321 .BR fcntl (2)
322 .BR F_DUPFD )
323 descriptor to the same
324 .B epoll
325 instance.
326 .\" But a descriptor duplicated by fork(2) can't be added to the
327 .\" set, because the [file *, fd] pair is already in the epoll set.
328 .\" That is a somewhat ugly inconsistency.  On the one hand, a child process
329 .\" cannot add the duplicate file descriptor to the epoll set.  (In every
330 .\" other case that I can think of, descriptors duplicated by fork have
331 .\" similar semantics to descriptors duplicated by dup() and friends.)  On
332 .\" the other hand, the very fact that the child has a duplicate of the
333 .\" descriptor means that even if the parent closes its descriptor, then
334 .\" epoll_wait() in the parent will continue to receive notifications for
335 .\" that descriptor because of the duplicated descriptor in the child.
336 .\"
337 .\" See http://thread.gmane.org/gmane.linux.kernel/596462/
338 .\" "epoll design problems with common fork/exec patterns"
339 .\"
340 .\" mtk, Feb 2008
341 This can be a useful technique for filtering events,
342 if the duplicate file descriptors are registered with different
343 .I events
344 masks.
345 .TP
346 .B Q2
347 Can two
348 .B epoll
349 instances wait for the same file descriptor?
350 If so, are events reported to both
351 .B epoll
352 file descriptors?
353 .TP
354 .B A2
355 Yes, and events would be reported to both.
356 However, careful programming may be needed to do this correctly.
357 .TP
358 .B Q3
359 Is the
360 .B epoll
361 file descriptor itself poll/epoll/selectable?
362 .TP
363 .B A3
364 Yes.
365 If an
366 .B epoll
367 file descriptor has events waiting, then it will
368 indicate as being readable.
369 .TP
370 .B Q4
371 What happens if one attempts to put an
372 .B epoll
373 file descriptor into its own file descriptor set?
374 .TP
375 .B A4
376 The
377 .BR epoll_ctl (2)
378 call will fail
379 .RB ( EINVAL ).
380 However, you can add an
381 .B epoll
382 file descriptor inside another
383 .B epoll
384 file descriptor set.
385 .TP
386 .B Q5
387 Can I send an
388 .B epoll
389 file descriptor over a UNIX domain socket to another process?
390 .TP
391 .B A5
392 Yes, but it does not make sense to do this, since the receiving process
393 would not have copies of the file descriptors in the
394 .B epoll
395 set.
396 .TP
397 .B Q6
398 Will closing a file descriptor cause it to be removed from all
399 .B epoll
400 sets automatically?
401 .TP
402 .B A6
403 Yes, but be aware of the following point.
404 A file descriptor is a reference to an open file description (see
405 .BR open (2)).
406 Whenever a descriptor is duplicated via
407 .BR dup (2),
408 .BR dup2 (2),
409 .BR fcntl (2)
410 .BR F_DUPFD ,
411 or
412 .BR fork (2),
413 a new file descriptor referring to the same open file description is
414 created.
415 An open file description continues to exist until all
416 file descriptors referring to it have been closed.
417 A file descriptor is removed from an
418 .B epoll
419 set only after all the file descriptors referring to the underlying
420 open file description have been closed
421 (or before if the descriptor is explicitly removed using
422 .BR epoll_ctl (2)
423 .BR EPOLL_CTL_DEL ).
424 This means that even after a file descriptor that is part of an
425 .B epoll
426 set has been closed,
427 events may be reported for that file descriptor if other file
428 descriptors referring to the same underlying file description remain open.
429 .TP
430 .B Q7
431 If more than one event occurs between
432 .BR epoll_wait (2)
433 calls, are they combined or reported separately?
434 .TP
435 .B A7
436 They will be combined.
437 .TP
438 .B Q8
439 Does an operation on a file descriptor affect the
440 already collected but not yet reported events?
441 .TP
442 .B A8
443 You can do two operations on an existing file descriptor.
444 Remove would be meaningless for
445 this case.
446 Modify will reread available I/O.
447 .TP
448 .B Q9
449 Do I need to continuously read/write a file descriptor
450 until
451 .B EAGAIN
452 when using the
453 .B EPOLLET
454 flag (edge-triggered behavior) ?
455 .TP
456 .B A9
457 Receiving an event from
458 .BR epoll_wait (2)
459 should suggest to you that such
460 file descriptor is ready for the requested I/O operation.
461 You must consider it ready until the next (nonblocking)
462 read/write yields
463 .BR EAGAIN .
464 When and how you will use the file descriptor is entirely up to you.
465 .sp
466 For packet/token-oriented files (e.g., datagram socket,
467 terminal in canonical mode),
468 the only way to detect the end of the read/write I/O space
469 is to continue to read/write until
470 .BR EAGAIN .
471 .sp
472 For stream-oriented files (e.g., pipe, FIFO, stream socket), the
473 condition that the read/write I/O space is exhausted can also be detected by
474 checking the amount of data read from / written to the target file
475 descriptor.
476 For example, if you call
477 .BR read (2)
478 by asking to read a certain amount of data and
479 .BR read (2)
480 returns a lower number of bytes, you
481 can be sure of having exhausted the read I/O space for the file
482 descriptor.
483 The same is true when writing using
484 .BR write (2).
485 (Avoid this latter technique if you cannot guarantee that
486 the monitored file descriptor always refers to a stream-oriented file.)
487 .SS Possible pitfalls and ways to avoid them
488 .TP
489 .B o Starvation (edge-triggered)
490 .PP
491 If there is a large amount of I/O space,
492 it is possible that by trying to drain
493 it the other files will not get processed causing starvation.
494 (This problem is not specific to
495 .BR epoll .)
496 .PP
497 The solution is to maintain a ready list
498 and mark the file descriptor as ready
499 in its associated data structure, thereby allowing the application to
500 remember which files need to be processed but still round robin amongst
501 all the ready files.
502 This also supports ignoring subsequent events you
503 receive for file descriptors that are already ready.
504 .TP
505 .B o If using an event cache...
506 .PP
507 If you use an event cache or store all the file descriptors returned from
508 .BR epoll_wait (2),
509 then make sure to provide a way to mark
510 its closure dynamically (i.e., caused by
511 a previous event's processing).
512 Suppose you receive 100 events from
513 .BR epoll_wait (2),
514 and in event #47 a condition causes event #13 to be closed.
515 If you remove the structure and
516 .BR close (2)
517 the file descriptor for event #13, then your
518 event cache might still say there are events waiting for that
519 file descriptor causing confusion.
520 .PP
521 One solution for this is to call, during the processing of event 47,
522 .BR epoll_ctl ( EPOLL_CTL_DEL )
523 to delete file descriptor 13 and
524 .BR close (2),
525 then mark its associated
526 data structure as removed and link it to a cleanup list.
527 If you find another
528 event for file descriptor 13 in your batch processing,
529 you will discover the file descriptor had been
530 previously removed and there will be no confusion.
531 .SH VERSIONS
532 The
533 .B epoll
534 API was introduced in Linux kernel 2.5.44.
535 .\" Its interface should be finalized in Linux kernel 2.5.66.
536 Support was added to glibc in version 2.3.2.
537 .SH CONFORMING TO
538 The
539 .B epoll
540 API is Linux-specific.
541 Some other systems provide similar
542 mechanisms, for example, FreeBSD has
543 .IR kqueue ,
544 and Solaris has
545 .IR /dev/poll .
546 .SH SEE ALSO
547 .BR epoll_create (2),
548 .BR epoll_create1 (2),
549 .BR epoll_ctl (2),
550 .BR epoll_wait (2)
551 .SH COLOPHON
552 This page is part of release 3.67 of the Linux
553 .I man-pages
554 project.
555 A description of the project,
556 information about reporting bugs,
557 and the latest version of this page,
558 can be found at
559 \%http://www.kernel.org/doc/man\-pages/.