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 <signal.h>
15       #include <poll.h>
16
17       int ppoll(struct pollfd *fds, nfds_t nfds,
18               const struct timespec *tmo_p, const sigset_t *sigmask);
19

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

VERSIONS

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

CONFORMING TO

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

NOTES

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

BUGS

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

EXAMPLES

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

SEE ALSO

398       restart_syscall(2), select(2), select_tut(2), epoll(7), time(7)
399

COLOPHON

401       This  page  is  part of release 5.07 of the Linux man-pages project.  A
402       description of the project, information about reporting bugs,  and  the
403       latest     version     of     this    page,    can    be    found    at
404       https://www.kernel.org/doc/man-pages/.
405
406
407
408Linux                             2020-04-11                           POLL(2)
Impressum