1poll(2)                       System Calls Manual                      poll(2)
2
3
4

NAME

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

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

VERSIONS

209       On  some  other  UNIX systems, poll() can fail with the error EAGAIN if
210       the system fails to allocate  kernel-internal  resources,  rather  than
211       ENOMEM  as Linux does.  POSIX permits this behavior.  Portable programs
212       may wish to check for EAGAIN and loop, just as with EINTR.
213
214       Some implementations define the nonstandard constant  INFTIM  with  the
215       value  -1  for  use as a timeout for poll().  This constant is not pro‐
216       vided in glibc.
217
218   C library/kernel differences
219       The Linux ppoll() system call modifies its  tmo_p  argument.   However,
220       the  glibc  wrapper function hides this behavior by using a local vari‐
221       able for the timeout argument that is passed to the system call.  Thus,
222       the glibc ppoll() function does not modify its tmo_p argument.
223
224       The  raw  ppoll()  system call has a fifth argument, size_t sigsetsize,
225       which specifies the size in bytes of the sigmask argument.   The  glibc
226       ppoll()  wrapper  function  specifies  this  argument  as a fixed value
227       (equal to sizeof(kernel_sigset_t)).  See sigprocmask(2) for  a  discus‐
228       sion  on  the differences between the kernel and the libc notion of the
229       sigset.
230

STANDARDS

232       poll() POSIX.1-2008.
233
234       ppoll()
235              Linux.
236

HISTORY

238       poll() POSIX.1-2001.  Linux 2.1.23.
239
240              On older kernels that lack this system call,  the  glibc  poll()
241              wrapper function provides emulation using select(2).
242
243       ppoll()
244              Linux 2.6.16, glibc 2.4.
245

NOTES

247       The  operation  of poll() and ppoll() is not affected by the O_NONBLOCK
248       flag.
249
250       For a discussion of what may happen if a file  descriptor  being  moni‐
251       tored by poll() is closed in another thread, see select(2).
252

BUGS

254       See  the  discussion of spurious readiness notifications under the BUGS
255       section of select(2).
256

EXAMPLES

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

SEE ALSO

401       restart_syscall(2),  select(2),  select_tut(2),  timespec(3), epoll(7),
402       time(7)
403
404
405
406Linux man-pages 6.05              2023-07-08                           poll(2)
Impressum