1POLL(2)                    Linux Programmer's Manual                   POLL(2)
2
3
4

NAME

6       poll, ppoll - wait for some event on a file descriptor
7

SYNOPSIS

9       #include <poll.h>
10
11       int poll(struct pollfd *fds, nfds_t nfds, int timeout);
12
13       #define _GNU_SOURCE         /* See feature_test_macros(7) */
14       #include <poll.h>
15
16       int ppoll(struct pollfd *fds, nfds_t nfds,
17                 const struct timespec *tmo_p, const sigset_t *sigmask);
18

DESCRIPTION

20       poll()  performs a similar task to select(2): it waits for one of a set
21       of file descriptors to become ready to perform I/O.  The Linux-specific
22       epoll(7)  API performs a similar task, but offers features beyond those
23       found in poll().
24
25       The set of file descriptors to be monitored is specified in the fds ar‐
26       gument, which is an array of structures of the following form:
27
28           struct pollfd {
29               int   fd;         /* file descriptor */
30               short events;     /* requested events */
31               short revents;    /* returned events */
32           };
33
34       The caller should specify the number of items in the fds array in nfds.
35
36       The  field  fd  contains  a  file descriptor for an open file.  If this
37       field is negative, then the corresponding events field is  ignored  and
38       the revents field returns zero.  (This provides an easy way of ignoring
39       a file descriptor for a single poll() call: simply negate the fd field.
40       Note,  however,  that  this  technique can't be used to ignore file de‐
41       scriptor 0.)
42
43       The field events is an input  parameter,  a  bit  mask  specifying  the
44       events  the  application  is  interested in for the file descriptor fd.
45       This field may be specified as zero, in which case the only events that
46       can  be returned in revents are POLLHUP, POLLERR, and POLLNVAL (see be‐
47       low).
48
49       The field revents is an output parameter, filled by the kernel with the
50       events  that  actually  occurred.  The bits returned in revents can in‐
51       clude any of those specified in events, or one of the  values  POLLERR,
52       POLLHUP,  or POLLNVAL.  (These three bits are meaningless in the events
53       field, and will be set in the revents field whenever the  corresponding
54       condition is true.)
55
56       If  none of the events requested (and no error) has occurred for any of
57       the file descriptors, then poll() blocks until one of  the  events  oc‐
58       curs.
59
60       The  timeout  argument specifies the number of milliseconds that poll()
61       should block waiting for a file descriptor to become ready.   The  call
62       will block until either:
63
64       • a file descriptor becomes ready;
65
66       • the call is interrupted by a signal handler; or
67
68       • the timeout expires.
69
70       Note  that  the timeout interval will be rounded up to the system clock
71       granularity, and kernel scheduling delays mean that the blocking inter‐
72       val  may  overrun  by  a  small amount.  Specifying a negative value in
73       timeout means an infinite timeout.  Specifying a timeout of zero causes
74       poll() to return immediately, even if no file descriptors are ready.
75
76       The  bits that may be set/returned in events and revents are defined in
77       <poll.h>:
78
79       POLLIN There is data to read.
80
81       POLLPRI
82              There is some exceptional  condition  on  the  file  descriptor.
83              Possibilities include:
84
85              • There is out-of-band data on a TCP socket (see tcp(7)).
86
87              • A pseudoterminal master in packet mode has seen a state change
88                on the slave (see ioctl_tty(2)).
89
90              • A cgroup.events file has been modified (see cgroups(7)).
91
92       POLLOUT
93              Writing is now possible, though a write larger than  the  avail‐
94              able  space  in a socket or pipe will still block (unless O_NON‐
95              BLOCK is set).
96
97       POLLRDHUP (since Linux 2.6.17)
98              Stream socket peer closed connection, or shut down writing  half
99              of  connection.   The _GNU_SOURCE feature test macro must be de‐
100              fined (before including any header files)  in  order  to  obtain
101              this definition.
102
103       POLLERR
104              Error  condition  (only returned in revents; ignored in events).
105              This bit is also set for a  file  descriptor  referring  to  the
106              write end of a pipe when the read end has been closed.
107
108       POLLHUP
109              Hang  up  (only  returned  in revents; ignored in events).  Note
110              that when reading from a channel such as  a  pipe  or  a  stream
111              socket, this event merely indicates that the peer closed its end
112              of the channel.  Subsequent reads from the channel will return 0
113              (end of file) only after all outstanding data in the channel has
114              been consumed.
115
116       POLLNVAL
117              Invalid request: fd not open (only returned in revents;  ignored
118              in events).
119
120       When  compiling with _XOPEN_SOURCE defined, one also has the following,
121       which convey no further information beyond the bits listed above:
122
123       POLLRDNORM
124              Equivalent to POLLIN.
125
126       POLLRDBAND
127              Priority band data can be read (generally unused on Linux).
128
129       POLLWRNORM
130              Equivalent to POLLOUT.
131
132       POLLWRBAND
133              Priority data may be written.
134
135       Linux also knows about, but does not use POLLMSG.
136
137   ppoll()
138       The relationship between poll() and ppoll() is analogous to  the  rela‐
139       tionship between select(2) and pselect(2): like pselect(2), ppoll() al‐
140       lows an application to safely wait until either a file  descriptor  be‐
141       comes ready or until a signal is caught.
142
143       Other than the difference in the precision of the timeout argument, the
144       following ppoll() call:
145
146           ready = ppoll(&fds, nfds, tmo_p, &sigmask);
147
148       is nearly equivalent to atomically executing the following calls:
149
150           sigset_t origmask;
151           int timeout;
152
153           timeout = (tmo_p == NULL) ? -1 :
154                     (tmo_p->tv_sec * 1000 + tmo_p->tv_nsec / 1000000);
155           pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);
156           ready = poll(&fds, nfds, timeout);
157           pthread_sigmask(SIG_SETMASK, &origmask, NULL);
158
159       The above code  segment  is  described  as  nearly  equivalent  because
160       whereas  a negative timeout value for poll() is interpreted as an infi‐
161       nite timeout, a negative value expressed in *tmo_p results in an  error
162       from ppoll().
163
164       See  the description of pselect(2) for an explanation of why ppoll() is
165       necessary.
166
167       If the sigmask argument is specified as NULL, then no signal  mask  ma‐
168       nipulation  is  performed (and thus ppoll() differs from poll() only in
169       the precision of the timeout argument).
170
171       The tmo_p argument specifies an upper limit on the amount of time  that
172       ppoll()  will  block.  This argument is a pointer to a structure of the
173       following form:
174
175           struct timespec {
176               long    tv_sec;         /* seconds */
177               long    tv_nsec;        /* nanoseconds */
178           };
179
180       If tmo_p is specified as NULL, then ppoll() can block indefinitely.
181

RETURN VALUE

183       On success, poll() returns a nonnegative value which is the  number  of
184       elements in the pollfds whose revents fields have been set to a nonzero
185       value (indicating an event or an error).  A return value of zero  indi‐
186       cates that the system call timed out before any file descriptors became
187       read.
188
189       On error, -1 is returned, and errno is set to indicate the error.
190

ERRORS

192       EFAULT fds points outside the process's accessible address space.   The
193              array  given  as  argument was not contained in the calling pro‐
194              gram's address space.
195
196       EINTR  A signal occurred before any requested event; see signal(7).
197
198       EINVAL The nfds value exceeds the RLIMIT_NOFILE value.
199
200       EINVAL (ppoll()) The timeout value expressed in *ip is  invalid  (nega‐
201              tive).
202
203       ENOMEM Unable to allocate memory for kernel data structures.
204

VERSIONS

206       The  poll()  system call was introduced in Linux 2.1.23.  On older ker‐
207       nels that lack this system call, the glibc poll() wrapper function pro‐
208       vides emulation using select(2).
209
210       The  ppoll()  system  call  was  added  to Linux in kernel 2.6.16.  The
211       ppoll() library call was added in glibc 2.4.
212

CONFORMING TO

214       poll() conforms to POSIX.1-2001 and POSIX.1-2008.   ppoll()  is  Linux-
215       specific.
216

NOTES

218       The  operation  of poll() and ppoll() is not affected by the O_NONBLOCK
219       flag.
220
221       On some other UNIX systems, poll() can fail with the  error  EAGAIN  if
222       the  system  fails  to  allocate kernel-internal resources, rather than
223       ENOMEM as Linux does.  POSIX permits this behavior.  Portable  programs
224       may wish to check for EAGAIN and loop, just as with EINTR.
225
226       Some  implementations  define  the nonstandard constant INFTIM with the
227       value -1 for use as a timeout for poll().  This constant  is  not  pro‐
228       vided in glibc.
229
230       For  a  discussion  of what may happen if a file descriptor being moni‐
231       tored by poll() is closed in another thread, see select(2).
232
233   C library/kernel differences
234       The Linux ppoll() system call modifies its  tmo_p  argument.   However,
235       the  glibc  wrapper function hides this behavior by using a local vari‐
236       able for the timeout argument that is passed to the system call.  Thus,
237       the glibc ppoll() function does not modify its tmo_p argument.
238
239       The  raw  ppoll()  system call has a fifth argument, size_t sigsetsize,
240       which specifies the size in bytes of the sigmask argument.   The  glibc
241       ppoll()  wrapper  function  specifies  this  argument  as a fixed value
242       (equal to sizeof(kernel_sigset_t)).  See sigprocmask(2) for  a  discus‐
243       sion  on  the differences between the kernel and the libc notion of the
244       sigset.
245

BUGS

247       See the discussion of spurious readiness notifications under  the  BUGS
248       section of select(2).
249

EXAMPLES

251       The program below opens each of the files named in its command-line ar‐
252       guments and monitors the resulting file descriptors  for  readiness  to
253       read  (POLLIN).   The program loops, repeatedly using poll() to monitor
254       the file descriptors, printing the number of ready file descriptors  on
255       return.  For each ready file descriptor, the program:
256
257       • displays the returned revents field in a human-readable form;
258
259       • if the file descriptor is readable, reads some data from it, and dis‐
260         plays that data on standard output; and
261
262       • if the file descriptors was not readable, but some  other  event  oc‐
263         curred (presumably POLLHUP), closes the file descriptor.
264
265       Suppose we run the program in one terminal, asking it to open a FIFO:
266
267           $ mkfifo myfifo
268           $ ./poll_input myfifo
269
270       In  a  second terminal window, we then open the FIFO for writing, write
271       some data to it, and close the FIFO:
272
273           $ echo aaaaabbbbbccccc > myfifo
274
275       In the terminal where we are running the program, we would then see:
276
277           Opened "myfifo" on fd 3
278           About to poll()
279           Ready: 1
280             fd=3; events: POLLIN POLLHUP
281               read 10 bytes: aaaaabbbbb
282           About to poll()
283           Ready: 1
284             fd=3; events: POLLIN POLLHUP
285               read 6 bytes: ccccc
286
287           About to poll()
288           Ready: 1
289             fd=3; events: POLLHUP
290               closing fd 3
291           All file descriptors closed; bye
292
293       In the above output, we see that poll() returned three times:
294
295       • On the first return, the bits returned  in  the  revents  field  were
296         POLLIN, indicating that the file descriptor is readable, and POLLHUP,
297         indicating that the other end of the FIFO has been closed.  The  pro‐
298         gram then consumed some of the available input.
299
300       • The  second return from poll() also indicated POLLIN and POLLHUP; the
301         program then consumed the last of the available input.
302
303       • On the final return, poll() indicated only POLLHUP on  the  FIFO,  at
304         which  point  the  file  descriptor was closed and the program termi‐
305         nated.
306
307   Program source
308
309       /* poll_input.c
310
311          Licensed under GNU General Public License v2 or later.
312       */
313       #include <poll.h>
314       #include <fcntl.h>
315       #include <sys/types.h>
316       #include <stdio.h>
317       #include <stdlib.h>
318       #include <unistd.h>
319
320       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
321                               } while (0)
322
323       int
324       main(int argc, char *argv[])
325       {
326           int nfds, num_open_fds;
327           struct pollfd *pfds;
328
329           if (argc < 2) {
330              fprintf(stderr, "Usage: %s file...\n", argv[0]);
331              exit(EXIT_FAILURE);
332           }
333
334           num_open_fds = nfds = argc - 1;
335           pfds = calloc(nfds, sizeof(struct pollfd));
336           if (pfds == NULL)
337               errExit("malloc");
338
339           /* Open each file on command line, and add it 'pfds' array. */
340
341           for (int j = 0; j < nfds; j++) {
342               pfds[j].fd = open(argv[j + 1], O_RDONLY);
343               if (pfds[j].fd == -1)
344                   errExit("open");
345
346               printf("Opened \"%s\" on fd %d\n", argv[j + 1], pfds[j].fd);
347
348               pfds[j].events = POLLIN;
349           }
350
351           /* Keep calling poll() as long as at least one file descriptor is
352              open. */
353
354           while (num_open_fds > 0) {
355               int ready;
356
357               printf("About to poll()\n");
358               ready = poll(pfds, nfds, -1);
359               if (ready == -1)
360                   errExit("poll");
361
362               printf("Ready: %d\n", ready);
363
364               /* Deal with array returned by poll(). */
365
366               for (int j = 0; j < nfds; j++) {
367                   char buf[10];
368
369                   if (pfds[j].revents != 0) {
370                       printf("  fd=%d; events: %s%s%s\n", pfds[j].fd,
371                               (pfds[j].revents & POLLIN)  ? "POLLIN "  : "",
372                               (pfds[j].revents & POLLHUP) ? "POLLHUP " : "",
373                               (pfds[j].revents & POLLERR) ? "POLLERR " : "");
374
375                       if (pfds[j].revents & POLLIN) {
376                           ssize_t s = read(pfds[j].fd, buf, sizeof(buf));
377                           if (s == -1)
378                               errExit("read");
379                           printf("    read %zd bytes: %.*s\n",
380                                   s, (int) s, buf);
381                       } else {                /* POLLERR | POLLHUP */
382                           printf("    closing fd %d\n", pfds[j].fd);
383                           if (close(pfds[j].fd) == -1)
384                               errExit("close");
385                           num_open_fds--;
386                       }
387                   }
388               }
389           }
390
391           printf("All file descriptors closed; bye\n");
392           exit(EXIT_SUCCESS);
393       }
394

SEE ALSO

396       restart_syscall(2), select(2), select_tut(2), epoll(7), time(7)
397

COLOPHON

399       This page is part of release 5.12 of the Linux  man-pages  project.   A
400       description  of  the project, information about reporting bugs, and the
401       latest    version    of    this    page,    can     be     found     at
402       https://www.kernel.org/doc/man-pages/.
403
404
405
406Linux                             2021-03-22                           POLL(2)
Impressum