namespaces.7: ffix
[man-pages.git] / man2 / poll.2
blob205468f3e6e8b8938c252382ef03e150dab3e09a
1 .\" Copyright (C) 2006, 2019 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
7 .\"
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
12 .\"
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein.  The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" %%%LICENSE_END
24 .\"
25 .\" Additions from Richard Gooch <rgooch@atnf.CSIRO.AU> and aeb, 971207
26 .\" 2006-03-13, mtk, Added ppoll() + various other rewordings
27 .\" 2006-07-01, mtk, Added POLLRDHUP + various other wording and
28 .\"     formatting changes.
29 .\"
30 .TH POLL 2 2021-03-22 "Linux" "Linux Programmer's Manual"
31 .SH NAME
32 poll, ppoll \- wait for some event on a file descriptor
33 .SH SYNOPSIS
34 .nf
35 .B #include <poll.h>
36 .PP
37 .BI "int poll(struct pollfd *" fds ", nfds_t " nfds ", int " timeout );
38 .PP
39 .BR "#define _GNU_SOURCE" "         /* See feature_test_macros(7) */"
40 .B #include <poll.h>
41 .PP
42 .BI "int ppoll(struct pollfd *" fds ", nfds_t " nfds ,
43 .BI "          const struct timespec *" tmo_p ", const sigset_t *" sigmask );
44 .fi
45 .SH DESCRIPTION
46 .BR poll ()
47 performs a similar task to
48 .BR select (2):
49 it waits for one of a set of file descriptors to become ready
50 to perform I/O.
51 The Linux-specific
52 .BR epoll (7)
53 API performs a similar task, but offers features beyond those found in
54 .BR poll ().
55 .PP
56 The set of file descriptors to be monitored is specified in the
57 .I fds
58 argument, which is an array of structures of the following form:
59 .PP
60 .in +4n
61 .EX
62 struct pollfd {
63     int   fd;         /* file descriptor */
64     short events;     /* requested events */
65     short revents;    /* returned events */
67 .EE
68 .in
69 .PP
70 The caller should specify the number of items in the
71 .I fds
72 array in
73 .IR nfds .
74 .PP
75 The field
76 .I fd
77 contains a file descriptor for an open file.
78 If this field is negative, then the corresponding
79 .I events
80 field is ignored and the
81 .I revents
82 field returns zero.
83 (This provides an easy way of ignoring a
84 file descriptor for a single
85 .BR poll ()
86 call: simply negate the
87 .I fd
88 field.
89 Note, however, that this technique can't be used to ignore file descriptor 0.)
90 .PP
91 The field
92 .I events
93 is an input parameter, a bit mask specifying the events the application
94 is interested in for the file descriptor
95 .IR fd .
96 This field may be specified as zero,
97 in which case the only events that can be returned in
98 .I revents
99 are
100 .BR POLLHUP ,
101 .BR POLLERR ,
103 .B POLLNVAL
104 (see below).
106 The field
107 .I revents
108 is an output parameter, filled by the kernel with the events that
109 actually occurred.
110 The bits returned in
111 .I revents
112 can include any of those specified in
113 .IR events ,
114 or one of the values
115 .BR POLLERR ,
116 .BR POLLHUP ,
118 .BR POLLNVAL .
119 (These three bits are meaningless in the
120 .I events
121 field, and will be set in the
122 .I revents
123 field whenever the corresponding condition is true.)
125 If none of the events requested (and no error) has occurred for any
126 of the file descriptors, then
127 .BR poll ()
128 blocks until one of the events occurs.
131 .I timeout
132 argument specifies the number of milliseconds that
133 .BR poll ()
134 should block waiting for a file descriptor to become ready.
135 The call will block until either:
136 .IP \(bu 2
137 a file descriptor becomes ready;
138 .IP \(bu
139 the call is interrupted by a signal handler; or
140 .IP \(bu
141 the timeout expires.
143 Note that the
144 .I timeout
145 interval will be rounded up to the system clock granularity,
146 and kernel scheduling delays mean that the blocking interval
147 may overrun by a small amount.
148 Specifying a negative value in
149 .I timeout
150 means an infinite timeout.
151 Specifying a
152 .I timeout
153 of zero causes
154 .BR poll ()
155 to return immediately, even if no file descriptors are ready.
157 The bits that may be set/returned in
158 .I events
160 .I revents
161 are defined in \fI<poll.h>\fP:
163 .B POLLIN
164 There is data to read.
166 .B POLLPRI
167 There is some exceptional condition on the file descriptor.
168 Possibilities include:
170 .IP \(bu 2
171 There is out-of-band data on a TCP socket (see
172 .BR tcp (7)).
173 .IP \(bu
174 A pseudoterminal master in packet mode has seen a state change on the slave
175 (see
176 .BR ioctl_tty (2)).
177 .IP \(bu
179 .I cgroup.events
180 file has been modified (see
181 .BR cgroups (7)).
184 .B POLLOUT
185 Writing is now possible, though a write larger than the available space
186 in a socket or pipe will still block (unless
187 .B O_NONBLOCK
188 is set).
190 .BR POLLRDHUP " (since Linux 2.6.17)"
191 Stream socket peer closed connection,
192 or shut down writing half of connection.
194 .B _GNU_SOURCE
195 feature test macro must be defined
196 (before including
197 .I any
198 header files)
199 in order to obtain this definition.
201 .B POLLERR
202 Error condition (only returned in
203 .IR revents ;
204 ignored in
205 .IR events ).
206 This bit is also set for a file descriptor referring
207 to the write end of a pipe when the read end has been closed.
209 .B POLLHUP
210 Hang up (only returned in
211 .IR revents ;
212 ignored in
213 .IR events ).
214 Note that when reading from a channel such as a pipe or a stream socket,
215 this event merely indicates that the peer closed its end of the channel.
216 Subsequent reads from the channel will return 0 (end of file)
217 only after all outstanding data in the channel has been consumed.
219 .B POLLNVAL
220 Invalid request:
221 .I fd
222 not open (only returned in
223 .IR revents ;
224 ignored in
225 .IR events ).
227 When compiling with
228 .B _XOPEN_SOURCE
229 defined, one also has the following,
230 which convey no further information beyond the bits listed above:
232 .B POLLRDNORM
233 Equivalent to
234 .BR POLLIN .
236 .B POLLRDBAND
237 Priority band data can be read (generally unused on Linux).
238 .\" POLLRDBAND is used in the DECnet protocol.
240 .B POLLWRNORM
241 Equivalent to
242 .BR POLLOUT .
244 .B POLLWRBAND
245 Priority data may be written.
247 Linux also knows about, but does not use
248 .BR POLLMSG .
249 .SS ppoll()
250 The relationship between
251 .BR poll ()
253 .BR ppoll ()
254 is analogous to the relationship between
255 .BR select (2)
257 .BR pselect (2):
258 like
259 .BR pselect (2),
260 .BR ppoll ()
261 allows an application to safely wait until either a file descriptor
262 becomes ready or until a signal is caught.
264 Other than the difference in the precision of the
265 .I timeout
266 argument, the following
267 .BR ppoll ()
268 call:
270 .in +4n
272 ready = ppoll(&fds, nfds, tmo_p, &sigmask);
276 is nearly equivalent to
277 .I atomically
278 executing the following calls:
280 .in +4n
282 sigset_t origmask;
283 int timeout;
285 timeout = (tmo_p == NULL) ? \-1 :
286           (tmo_p\->tv_sec * 1000 + tmo_p\->tv_nsec / 1000000);
287 pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);
288 ready = poll(&fds, nfds, timeout);
289 pthread_sigmask(SIG_SETMASK, &origmask, NULL);
293 The above code segment is described as
294 .I nearly
295 equivalent because whereas a negative
296 .I timeout
297 value for
298 .BR poll ()
299 is interpreted as an infinite timeout, a negative value expressed in
300 .IR *tmo_p
301 results in an error from
302 .BR ppoll ().
304 See the description of
305 .BR pselect (2)
306 for an explanation of why
307 .BR ppoll ()
308 is necessary.
310 If the
311 .I sigmask
312 argument is specified as NULL, then
313 no signal mask manipulation is performed
314 (and thus
315 .BR ppoll ()
316 differs from
317 .BR poll ()
318 only in the precision of the
319 .I timeout
320 argument).
323 .I tmo_p
324 argument specifies an upper limit on the amount of time that
325 .BR ppoll ()
326 will block.
327 This argument is a pointer to a structure of the following form:
329 .in +4n
331 struct timespec {
332     long    tv_sec;         /* seconds */
333     long    tv_nsec;        /* nanoseconds */
339 .I tmo_p
340 is specified as NULL, then
341 .BR ppoll ()
342 can block indefinitely.
343 .SH RETURN VALUE
344 On success,
345 .BR poll ()
346 returns a nonnegative value which is the number of elements in the
347 .I pollfds
348 whose
349 .I revents
350 fields have been set to a nonzero value (indicating an event or an error).
351 A return value of zero indicates that the system call timed out
352 before any file descriptors became read.
354 On error, \-1 is returned, and
355 .I errno
356 is set to indicate the error.
357 .SH ERRORS
359 .B EFAULT
360 .I fds
361 points outside the process's accessible address space.
362 The array given as argument was not contained in the calling program's
363 address space.
365 .B EINTR
366 A signal occurred before any requested event; see
367 .BR signal (7).
369 .B EINVAL
371 .I nfds
372 value exceeds the
373 .B RLIMIT_NOFILE
374 value.
376 .B EINVAL
377 .RB ( ppoll ())
378 The timeout value expressed in
379 .IR *ip
380 is invalid (negative).
382 .B ENOMEM
383 Unable to allocate memory for kernel data structures.
384 .SH VERSIONS
386 .BR poll ()
387 system call was introduced in Linux 2.1.23.
388 On older kernels that lack this system call,
389 the glibc
390 .BR poll ()
391 wrapper function provides emulation using
392 .BR select (2).
395 .BR ppoll ()
396 system call was added to Linux in kernel 2.6.16.
398 .BR ppoll ()
399 library call was added in glibc 2.4.
400 .SH CONFORMING TO
401 .BR poll ()
402 conforms to POSIX.1-2001 and POSIX.1-2008.
403 .BR ppoll ()
404 is Linux-specific.
405 .\" FIXME .
406 .\" ppoll() is proposed for inclusion in POSIX:
407 .\" https://www.austingroupbugs.net/view.php?id=1263
408 .\" NetBSD 3.0 has a pollts() which is like Linux ppoll().
409 .SH NOTES
410 The operation of
411 .BR poll ()
413 .BR ppoll ()
414 is not affected by the
415 .BR O_NONBLOCK
416 flag.
418 On some other UNIX systems,
419 .\" Darwin, according to a report by Jeremy Sequoia, relayed by Josh Triplett
420 .BR poll ()
421 can fail with the error
422 .B EAGAIN
423 if the system fails to allocate kernel-internal resources, rather than
424 .B ENOMEM
425 as Linux does.
426 POSIX permits this behavior.
427 Portable programs may wish to check for
428 .B EAGAIN
429 and loop, just as with
430 .BR EINTR .
432 Some implementations define the nonstandard constant
433 .B INFTIM
434 with the value \-1 for use as a
435 .IR timeout
437 .BR poll ().
438 This constant is not provided in glibc.
440 For a discussion of what may happen if a file descriptor being monitored by
441 .BR poll ()
442 is closed in another thread, see
443 .BR select (2).
444 .SS C library/kernel differences
445 The Linux
446 .BR ppoll ()
447 system call modifies its
448 .I tmo_p
449 argument.
450 However, the glibc wrapper function hides this behavior
451 by using a local variable for the timeout argument that
452 is passed to the system call.
453 Thus, the glibc
454 .BR ppoll ()
455 function does not modify its
456 .I tmo_p
457 argument.
459 The raw
460 .BR ppoll ()
461 system call has a fifth argument,
462 .IR "size_t sigsetsize" ,
463 which specifies the size in bytes of the
464 .IR sigmask
465 argument.
466 The glibc
467 .BR ppoll ()
468 wrapper function specifies this argument as a fixed value
469 (equal to
470 .IR sizeof(kernel_sigset_t) ).
472 .BR sigprocmask (2)
473 for a discussion on the differences between the kernel and the libc
474 notion of the sigset.
475 .SH BUGS
476 See the discussion of spurious readiness notifications under the
477 BUGS section of
478 .BR select (2).
479 .SH EXAMPLES
480 The program below opens each of the files named in its command-line
481 arguments and monitors the resulting file descriptors for readiness to read
482 .RB ( POLLIN ).
483 The program loops, repeatedly using
484 .BR poll ()
485 to monitor the file descriptors,
486 printing the number of ready file descriptors on return.
487 For each ready file descriptor, the program:
488 .IP \(bu 2
489 displays the returned
490 .I revents
491 field in a human-readable form;
492 .IP \(bu
493 if the file descriptor is readable, reads some data from it,
494 and displays that data on standard output; and
495 .IP \(bu
496 if the file descriptors was not readable,
497 but some other event occurred (presumably
498 .BR POLLHUP ),
499 closes the file descriptor.
501 Suppose we run the program in one terminal, asking it to open a FIFO:
503 .in +4n
505 $ \fBmkfifo myfifo\fP
506 $ \fB./poll_input myfifo\fP
510 In a second terminal window, we then open the FIFO for writing,
511 write some data to it, and close the FIFO:
513 .in +4n
515 $ \fBecho aaaaabbbbbccccc > myfifo\fP
519 In the terminal where we are running the program, we would then see:
521 .in +4n
523 Opened "myfifo" on fd 3
524 About to poll()
525 Ready: 1
526   fd=3; events: POLLIN POLLHUP
527     read 10 bytes: aaaaabbbbb
528 About to poll()
529 Ready: 1
530   fd=3; events: POLLIN POLLHUP
531     read 6 bytes: ccccc
533 About to poll()
534 Ready: 1
535   fd=3; events: POLLHUP
536     closing fd 3
537 All file descriptors closed; bye
541 In the above output, we see that
542 .BR poll ()
543 returned three times:
544 .IP \(bu 2
545 On the first return, the bits returned in the
546 .I revents
547 field were
548 .BR POLLIN ,
549 indicating that the file descriptor is readable, and
550 .BR POLLHUP ,
551 indicating that the other end of the FIFO has been closed.
552 The program then consumed some of the available input.
553 .IP \(bu
554 The second return from
555 .BR poll ()
556 also indicated
557 .BR POLLIN
559 .BR POLLHUP ;
560 the program then consumed the last of the available input.
561 .IP \(bu
562 On the final return,
563 .BR poll ()
564 indicated only
565 .BR POLLHUP
566 on the FIFO,
567 at which point the file descriptor was closed and the program terminated.
569 .SS Program source
572 /* poll_input.c
574    Licensed under GNU General Public License v2 or later.
576 #include <poll.h>
577 #include <fcntl.h>
578 #include <sys/types.h>
579 #include <stdio.h>
580 #include <stdlib.h>
581 #include <unistd.h>
583 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
584                         } while (0)
587 main(int argc, char *argv[])
589     int nfds, num_open_fds;
590     struct pollfd *pfds;
592     if (argc < 2) {
593        fprintf(stderr, "Usage: %s file...\en", argv[0]);
594        exit(EXIT_FAILURE);
595     }
597     num_open_fds = nfds = argc \- 1;
598     pfds = calloc(nfds, sizeof(struct pollfd));
599     if (pfds == NULL)
600         errExit("malloc");
602     /* Open each file on command line, and add it \(aqpfds\(aq array. */
604     for (int j = 0; j < nfds; j++) {
605         pfds[j].fd = open(argv[j + 1], O_RDONLY);
606         if (pfds[j].fd == \-1)
607             errExit("open");
609         printf("Opened \e"%s\e" on fd %d\en", argv[j + 1], pfds[j].fd);
611         pfds[j].events = POLLIN;
612     }
614     /* Keep calling poll() as long as at least one file descriptor is
615        open. */
617     while (num_open_fds > 0) {
618         int ready;
620         printf("About to poll()\en");
621         ready = poll(pfds, nfds, \-1);
622         if (ready == \-1)
623             errExit("poll");
625         printf("Ready: %d\en", ready);
627         /* Deal with array returned by poll(). */
629         for (int j = 0; j < nfds; j++) {
630             char buf[10];
632             if (pfds[j].revents != 0) {
633                 printf("  fd=%d; events: %s%s%s\en", pfds[j].fd,
634                         (pfds[j].revents & POLLIN)  ? "POLLIN "  : "",
635                         (pfds[j].revents & POLLHUP) ? "POLLHUP " : "",
636                         (pfds[j].revents & POLLERR) ? "POLLERR " : "");
638                 if (pfds[j].revents & POLLIN) {
639                     ssize_t s = read(pfds[j].fd, buf, sizeof(buf));
640                     if (s == \-1)
641                         errExit("read");
642                     printf("    read %zd bytes: %.*s\en",
643                             s, (int) s, buf);
644                 } else {                /* POLLERR | POLLHUP */
645                     printf("    closing fd %d\en", pfds[j].fd);
646                     if (close(pfds[j].fd) == \-1)
647                         errExit("close");
648                     num_open_fds\-\-;
649                 }
650             }
651         }
652     }
654     printf("All file descriptors closed; bye\en");
655     exit(EXIT_SUCCESS);
658 .SH SEE ALSO
659 .BR restart_syscall (2),
660 .BR select (2),
661 .BR select_tut (2),
662 .BR epoll (7),
663 .BR time (7)