Changes.old: Add missing entry in 5.13 changelog
[man-pages.git] / man2 / select.2
blobaee25c52c0b0a335497aa336c6c9cbd69151b78b
1 .\" This manpage is copyright (C) 1992 Drew Eckhardt,
2 .\"     copyright (C) 1995 Michael Shields,
3 .\"     copyright (C) 2001 Paul Sheer,
4 .\"     copyright (C) 2006, 2019 Michael Kerrisk <mtk.manpages@gmail.com>
5 .\"
6 .\" %%%LICENSE_START(VERBATIM)
7 .\" Permission is granted to make and distribute verbatim copies of this
8 .\" manual provided the copyright notice and this permission notice are
9 .\" preserved on all copies.
10 .\"
11 .\" Permission is granted to copy and distribute modified versions of this
12 .\" manual under the conditions for verbatim copying, provided that the
13 .\" entire resulting derived work is distributed under the terms of a
14 .\" permission notice identical to this one.
15 .\"
16 .\" Since the Linux kernel and libraries are constantly changing, this
17 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
18 .\" responsibility for errors or omissions, or for damages resulting from
19 .\" the use of the information contained herein.  The author(s) may not
20 .\" have taken the same level of care in the production of this manual,
21 .\" which is licensed free of charge, as they might when working
22 .\" professionally.
23 .\"
24 .\" Formatted or processed versions of this manual, if unaccompanied by
25 .\" the source, must acknowledge the copyright and authors of this work.
26 .\" %%%LICENSE_END
27 .\"
28 .\" Modified 1993-07-24 by Rik Faith <faith@cs.unc.edu>
29 .\" Modified 1995-05-18 by Jim Van Zandt <jrv@vanzandt.mv.com>
30 .\" Sun Feb 11 14:07:00 MET 1996  Martin Schulze  <joey@linux.de>
31 .\"     * layout slightly modified
32 .\"
33 .\" Modified Mon Oct 21 23:05:29 EDT 1996 by Eric S. Raymond <esr@thyrsus.com>
34 .\" Modified Thu Feb 24 01:41:09 CET 2000 by aeb
35 .\" Modified Thu Feb  9 22:32:09 CET 2001 by bert hubert <ahu@ds9a.nl>, aeb
36 .\" Modified Mon Nov 11 14:35:00 PST 2002 by Ben Woodard <ben@zork.net>
37 .\" 2005-03-11, mtk, modified pselect() text (it is now a system
38 .\"     call in 2.6.16.
39 .\"
40 .TH SELECT 2 2021-03-22 "Linux" "Linux Programmer's Manual"
41 .SH NAME
42 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
43 synchronous I/O multiplexing
44 .SH SYNOPSIS
45 .nf
46 .B #include <sys/select.h>
47 .PP
48 .BI "int select(int " nfds ", fd_set *restrict " readfds ,
49 .BI "           fd_set *restrict " writefds ", fd_set *restrict " exceptfds ,
50 .BI "           struct timeval *restrict " timeout );
51 .PP
52 .BI "void FD_CLR(int " fd ", fd_set *" set );
53 .BI "int  FD_ISSET(int " fd ", fd_set *" set );
54 .BI "void FD_SET(int " fd ", fd_set *" set );
55 .BI "void FD_ZERO(fd_set *" set );
56 .PP
57 .BI "int pselect(int " nfds ", fd_set *restrict " readfds ,
58 .BI "           fd_set *restrict " writefds ", fd_set *restrict " exceptfds ,
59 .BI "           const struct timespec *restrict " timeout ,
60 .BI "           const sigset_t *restrict " sigmask );
61 .fi
62 .PP
63 .RS -4
64 Feature Test Macro Requirements for glibc (see
65 .BR feature_test_macros (7)):
66 .RE
67 .PP
68 .BR pselect ():
69 .nf
70     _POSIX_C_SOURCE >= 200112L
71 .fi
72 .SH DESCRIPTION
73 .BR "WARNING" :
74 .BR select ()
75 can monitor only file descriptors numbers that are less than
76 .BR FD_SETSIZE
77 (1024)\(eman unreasonably low limit for many modern applications\(emand
78 this limitation will not change.
79 All modern applications should instead use
80 .BR poll (2)
82 .BR epoll (7),
83 which do not suffer this limitation.
84 .PP
85 .BR select ()
86 allows a program to monitor multiple file descriptors,
87 waiting until one or more of the file descriptors become "ready"
88 for some class of I/O operation (e.g., input possible).
89 A file descriptor is considered ready if it is possible to
90 perform a corresponding I/O operation (e.g.,
91 .BR read (2),
92 or a sufficiently small
93 .BR write (2))
94 without blocking.
95 .\"
96 .SS File descriptor sets
97 The principal arguments of
98 .BR select ()
99 are three "sets" of file descriptors (declared with the type
100 .IR fd_set ),
101 which allow the caller to wait for three classes of events
102 on the specified set of file descriptors.
103 Each of the
104 .I fd_set
105 arguments may be specified as NULL if no file descriptors are
106 to be watched for the corresponding class of events.
108 .BR "Note well" :
109 Upon return, each of the file descriptor sets is modified in place
110 to indicate which file descriptors are currently "ready".
111 Thus, if using
112 .BR select ()
113 within a loop, the sets \fImust be reinitialized\fP before each call.
115 The contents of a file descriptor set can be manipulated
116 using the following macros:
118 .BR FD_ZERO ()
119 This macro clears (removes all file descriptors from)
120 .IR set .
121 It should be employed as the first step in initializing a file descriptor set.
123 .BR FD_SET ()
124 This macro adds the file descriptor
125 .I fd
127 .IR set .
128 Adding a file descriptor that is already present in the set is a no-op,
129 and does not produce an error.
131 .BR FD_CLR ()
132 This macro removes the file descriptor
133 .I fd
134 from
135 .IR set .
136 Removing a file descriptor that is not present in the set is a no-op,
137 and does not produce an error.
139 .BR FD_ISSET ()
140 .BR select ()
141 modifies the contents of the sets according to the rules
142 described below.
143 After calling
144 .BR select (),
146 .BR FD_ISSET ()
147 macro
148 can be used to test if a file descriptor is still present in a set.
149 .BR FD_ISSET ()
150 returns nonzero if the file descriptor
151 .I fd
152 is present in
153 .IR set ,
154 and zero if it is not.
156 .SS Arguments
157 The arguments of
158 .BR select ()
159 are as follows:
161 .I readfds
162 The file descriptors in this set are watched to see if they are
163 ready for reading.
164 A file descriptor is ready for reading if a read operation will not
165 block; in particular, a file descriptor is also ready on end-of-file.
167 After
168 .BR select ()
169 has returned, \fIreadfds\fP will be
170 cleared of all file descriptors except for those that are ready for reading.
172 .I writefds
173 The file descriptors in this set are watched to see if they are
174 ready for writing.
175 A file descriptor is ready for writing if a write operation will not block.
176 However, even if a file descriptor indicates as writable,
177 a large write may still block.
179 After
180 .BR select ()
181 has returned, \fIwritefds\fP will be
182 cleared of all file descriptors except for those that are ready for writing.
184 .I exceptfds
185 The file descriptors in this set are watched for "exceptional conditions".
186 For examples of some exceptional conditions, see the discussion of
187 .B POLLPRI
189 .BR poll (2).
191 After
192 .BR select ()
193 has returned,
194 \fIexceptfds\fP will be cleared of all file descriptors except for those
195 for which an exceptional condition has occurred.
197 .I nfds
198 This argument should be set to the highest-numbered file descriptor in any
199 of the three sets, plus 1.
200 The indicated file descriptors in each set are checked, up to this limit
201 (but see BUGS).
203 .I timeout
205 .I timeout
206 argument is a
207 .I timeval
208 structure (shown below) that specifies the interval that
209 .BR select ()
210 should block waiting for a file descriptor to become ready.
211 The call will block until either:
213 .IP \(bu 2
214 a file descriptor becomes ready;
215 .IP \(bu
216 the call is interrupted by a signal handler; or
217 .IP \(bu
218 the timeout expires.
221 Note that the
222 .I timeout
223 interval will be rounded up to the system clock granularity,
224 and kernel scheduling delays mean that the blocking interval
225 may overrun by a small amount.
227 If both fields of the
228 .I timeval
229 structure are zero, then
230 .BR select ()
231 returns immediately.
232 (This is useful for polling.)
235 .I timeout
236 is specified as NULL,
237 .BR select ()
238 blocks indefinitely waiting for a file descriptor to become ready.
240 .SS pselect()
242 .BR pselect ()
243 system call allows an application to safely wait until either
244 a file descriptor becomes ready or until a signal is caught.
246 The operation of
247 .BR select ()
249 .BR pselect ()
250 is identical, other than these three differences:
251 .IP \(bu 2
252 .BR select ()
253 uses a timeout that is a
254 .I struct timeval
255 (with seconds and microseconds), while
256 .BR pselect ()
257 uses a
258 .I struct timespec
259 (with seconds and nanoseconds).
260 .IP \(bu
261 .BR select ()
262 may update the
263 .I timeout
264 argument to indicate how much time was left.
265 .BR pselect ()
266 does not change this argument.
267 .IP \(bu
268 .BR select ()
269 has no
270 .I sigmask
271 argument, and behaves as
272 .BR pselect ()
273 called with NULL
274 .IR sigmask .
276 .I sigmask
277 is a pointer to a signal mask (see
278 .BR sigprocmask (2));
279 if it is not NULL, then
280 .BR pselect ()
281 first replaces the current signal mask by the one pointed to by
282 .IR sigmask ,
283 then does the "select" function, and then restores the original
284 signal mask.
286 .I sigmask
287 is NULL,
288 the signal mask is not modified during the
289 .BR pselect ()
290 call.)
292 Other than the difference in the precision of the
293 .I timeout
294 argument, the following
295 .BR pselect ()
296 call:
298 .in +4n
300 ready = pselect(nfds, &readfds, &writefds, &exceptfds,
301                 timeout, &sigmask);
305 is equivalent to
306 .I atomically
307 executing the following calls:
309 .in +4n
311 sigset_t origmask;
313 pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);
314 ready = select(nfds, &readfds, &writefds, &exceptfds, timeout);
315 pthread_sigmask(SIG_SETMASK, &origmask, NULL);
319 The reason that
320 .BR pselect ()
321 is needed is that if one wants to wait for either a signal
322 or for a file descriptor to become ready, then
323 an atomic test is needed to prevent race conditions.
324 (Suppose the signal handler sets a global flag and
325 returns.
326 Then a test of this global flag followed by a call of
327 .BR select ()
328 could hang indefinitely if the signal arrived just after the test
329 but just before the call.
330 By contrast,
331 .BR pselect ()
332 allows one to first block signals, handle the signals that have come in,
333 then call
334 .BR pselect ()
335 with the desired
336 .IR sigmask ,
337 avoiding the race.)
338 .SS The timeout
340 .I timeout
341 argument for
342 .BR select ()
343 is a structure of the following type:
345 .in +4n
347 struct timeval {
348     time_t      tv_sec;         /* seconds */
349     suseconds_t tv_usec;        /* microseconds */
354 The corresponding argument for
355 .BR pselect ()
356 has the following type:
358 .in +4n
360 struct timespec {
361     time_t      tv_sec;         /* seconds */
362     long        tv_nsec;        /* nanoseconds */
367 On Linux,
368 .BR select ()
369 modifies
370 .I timeout
371 to reflect the amount of time not slept; most other implementations
372 do not do this.
373 (POSIX.1 permits either behavior.)
374 This causes problems both when Linux code which reads
375 .I timeout
376 is ported to other operating systems, and when code is ported to Linux
377 that reuses a \fIstruct timeval\fP for multiple
378 .BR select ()s
379 in a loop without reinitializing it.
380 Consider
381 .I timeout
382 to be undefined after
383 .BR select ()
384 returns.
385 .\" .PP - it is rumored that:
386 .\" On BSD, when a timeout occurs, the file descriptor bits are not changed.
387 .\" - it is certainly true that:
388 .\" Linux follows SUSv2 and sets the bit masks to zero upon a timeout.
389 .SH RETURN VALUE
390 On success,
391 .BR select ()
393 .BR pselect ()
394 return the number of file descriptors contained in the three returned
395 descriptor sets (that is, the total number of bits that are set in
396 .IR readfds ,
397 .IR writefds ,
398 .IR exceptfds ).
399 The return value may be zero if the timeout expired before any
400 file descriptors became ready.
402 On error, \-1 is returned, and
403 .I errno
404 is set to indicate the error;
405 the file descriptor sets are unmodified,
407 .I timeout
408 becomes undefined.
409 .SH ERRORS
411 .B EBADF
412 An invalid file descriptor was given in one of the sets.
413 (Perhaps a file descriptor that was already closed,
414 or one on which an error has occurred.)
415 However, see BUGS.
417 .B EINTR
418 A signal was caught; see
419 .BR signal (7).
421 .B EINVAL
422 .I nfds
423 is negative or exceeds the
424 .BR RLIMIT_NOFILE
425 resource limit (see
426 .BR getrlimit (2)).
428 .B EINVAL
429 The value contained within
430 .I timeout
431 is invalid.
433 .B ENOMEM
434 Unable to allocate memory for internal tables.
435 .SH VERSIONS
436 .BR pselect ()
437 was added to Linux in kernel 2.6.16.
438 Prior to this,
439 .BR pselect ()
440 was emulated in glibc (but see BUGS).
441 .SH CONFORMING TO
442 .BR select ()
443 conforms to POSIX.1-2001, POSIX.1-2008, and
444 4.4BSD
445 .RB ( select ()
446 first appeared in 4.2BSD).
447 Generally portable to/from
448 non-BSD systems supporting clones of the BSD socket layer (including
449 System\ V variants).
450 However, note that the System\ V variant typically
451 sets the timeout variable before returning, but the BSD variant does not.
453 .BR pselect ()
454 is defined in POSIX.1g, and in
455 POSIX.1-2001 and POSIX.1-2008.
456 .SH NOTES
458 .I fd_set
459 is a fixed size buffer.
460 Executing
461 .BR FD_CLR ()
463 .BR FD_SET ()
464 with a value of
465 .I fd
466 that is negative or is equal to or larger than
467 .B FD_SETSIZE
468 will result
469 in undefined behavior.
470 Moreover, POSIX requires
471 .I fd
472 to be a valid file descriptor.
474 The operation of
475 .BR select ()
477 .BR pselect ()
478 is not affected by the
479 .BR O_NONBLOCK
480 flag.
482 On some other UNIX systems,
483 .\" Darwin, according to a report by Jeremy Sequoia, relayed by Josh Triplett
484 .BR select ()
485 can fail with the error
486 .B EAGAIN
487 if the system fails to allocate kernel-internal resources, rather than
488 .B ENOMEM
489 as Linux does.
490 POSIX specifies this error for
491 .BR poll (2),
492 but not for
493 .BR select ().
494 Portable programs may wish to check for
495 .B EAGAIN
496 and loop, just as with
497 .BR EINTR .
499 .SS The self-pipe trick
500 On systems that lack
501 .BR pselect (),
502 reliable (and more portable) signal trapping can be achieved
503 using the self-pipe trick.
504 In this technique,
505 a signal handler writes a byte to a pipe whose other end
506 is monitored by
507 .BR select ()
508 in the main program.
509 (To avoid possibly blocking when writing to a pipe that may be full
510 or reading from a pipe that may be empty,
511 nonblocking I/O is used when reading from and writing to the pipe.)
513 .SS Emulating usleep(3)
514 Before the advent of
515 .BR usleep (3),
516 some code employed a call to
517 .BR select ()
518 with all three sets empty,
519 .I nfds
520 zero, and a non-NULL
521 .I timeout
522 as a fairly portable way to sleep with subsecond precision.
524 .SS Correspondence between select() and poll() notifications
525 Within the Linux kernel source,
526 .\" fs/select.c
527 we find the following definitions which show the correspondence
528 between the readable, writable, and exceptional condition notifications of
529 .BR select ()
530 and the event notifications provided by
531 .BR poll (2)
533 .BR epoll (7):
535 .in +4n
537 #define POLLIN_SET  (EPOLLRDNORM | EPOLLRDBAND | EPOLLIN |
538                      EPOLLHUP | EPOLLERR)
539                    /* Ready for reading */
540 #define POLLOUT_SET (EPOLLWRBAND | EPOLLWRNORM | EPOLLOUT |
541                      EPOLLERR)
542                    /* Ready for writing */
543 #define POLLEX_SET  (EPOLLPRI)
544                    /* Exceptional condition */
548 .SS Multithreaded applications
549 If a file descriptor being monitored by
550 .BR select ()
551 is closed in another thread, the result is unspecified.
552 On some UNIX systems,
553 .BR select ()
554 unblocks and returns, with an indication that the file descriptor is ready
555 (a subsequent I/O operation will likely fail with an error,
556 unless another process reopens file descriptor between the time
557 .BR select ()
558 returned and the I/O operation is performed).
559 On Linux (and some other systems),
560 closing the file descriptor in another thread has no effect on
561 .BR select ().
562 In summary, any application that relies on a particular behavior
563 in this scenario must be considered buggy.
565 .SS C library/kernel differences
566 The Linux kernel allows file descriptor sets of arbitrary size,
567 determining the length of the sets to be checked from the value of
568 .IR nfds .
569 However, in the glibc implementation, the
570 .IR fd_set
571 type is fixed in size.
572 See also BUGS.
575 .BR pselect ()
576 interface described in this page is implemented by glibc.
577 The underlying Linux system call is named
578 .BR pselect6 ().
579 This system call has somewhat different behavior from the glibc
580 wrapper function.
582 The Linux
583 .BR pselect6 ()
584 system call modifies its
585 .I timeout
586 argument.
587 However, the glibc wrapper function hides this behavior
588 by using a local variable for the timeout argument that
589 is passed to the system call.
590 Thus, the glibc
591 .BR pselect ()
592 function does not modify its
593 .I timeout
594 argument;
595 this is the behavior required by POSIX.1-2001.
597 The final argument of the
598 .BR pselect6 ()
599 system call is not a
600 .I "sigset_t\ *"
601 pointer, but is instead a structure of the form:
603 .in +4n
605 struct {
606     const kernel_sigset_t *ss;   /* Pointer to signal set */
607     size_t ss_len;               /* Size (in bytes) of object
608                                     pointed to by \(aqss\(aq */
613 This allows the system call to obtain both
614 a pointer to the signal set and its size,
615 while allowing for the fact that most architectures
616 support a maximum of 6 arguments to a system call.
618 .BR sigprocmask (2)
619 for a discussion of the difference between the kernel and libc
620 notion of the signal set.
622 .SS Historical glibc details
623 Glibc 2.0 provided an incorrect version of
624 .BR pselect ()
625 that did not take a
626 .I sigmask
627 argument.
629 In glibc versions 2.1 to 2.2.1,
630 one must define
631 .B _GNU_SOURCE
632 in order to obtain the declaration of
633 .BR pselect ()
634 from
635 .IR <sys/select.h> .
636 .SH BUGS
637 POSIX allows an implementation to define an upper limit,
638 advertised via the constant
639 .BR FD_SETSIZE ,
640 on the range of file descriptors that can be specified
641 in a file descriptor set.
642 The Linux kernel imposes no fixed limit, but the glibc implementation makes
643 .IR fd_set
644 a fixed-size type, with
645 .BR FD_SETSIZE
646 defined as 1024, and the
647 .BR FD_* ()
648 macros operating according to that limit.
649 To monitor file descriptors greater than 1023, use
650 .BR poll (2)
652 .BR epoll (7)
653 instead.
655 The implementation of the
656 .I fd_set
657 arguments as value-result arguments is a design error that is avoided in
658 .BR poll (2)
660 .BR epoll (7).
662 According to POSIX,
663 .BR select ()
664 should check all specified file descriptors in the three file descriptor sets,
665 up to the limit
666 .IR nfds\-1 .
667 However, the current implementation ignores any file descriptor in
668 these sets that is greater than the maximum file descriptor number
669 that the process currently has open.
670 According to POSIX, any such file descriptor that is specified in one
671 of the sets should result in the error
672 .BR EBADF .
674 Starting with version 2.1, glibc provided an emulation of
675 .BR pselect ()
676 that was implemented using
677 .BR sigprocmask (2)
679 .BR select ().
680 This implementation remained vulnerable to the very race condition that
681 .BR pselect ()
682 was designed to prevent.
683 Modern versions of glibc use the (race-free)
684 .BR pselect ()
685 system call on kernels where it is provided.
687 On Linux,
688 .BR select ()
689 may report a socket file descriptor as "ready for reading", while
690 nevertheless a subsequent read blocks.
691 This could for example
692 happen when data has arrived but upon examination has the wrong
693 checksum and is discarded.
694 There may be other circumstances
695 in which a file descriptor is spuriously reported as ready.
696 .\" Stevens discusses a case where accept can block after select
697 .\" returns successfully because of an intervening RST from the client.
698 Thus it may be safer to use
699 .B O_NONBLOCK
700 on sockets that should not block.
701 .\" Maybe the kernel should have returned EIO in such a situation?
703 On Linux,
704 .BR select ()
705 also modifies
706 .I timeout
707 if the call is interrupted by a signal handler (i.e., the
708 .B EINTR
709 error return).
710 This is not permitted by POSIX.1.
711 The Linux
712 .BR pselect ()
713 system call has the same behavior,
714 but the glibc wrapper hides this behavior by internally copying the
715 .I timeout
716 to a local variable and passing that variable to the system call.
717 .SH EXAMPLES
719 #include <stdio.h>
720 #include <stdlib.h>
721 #include <sys/select.h>
724 main(void)
726     fd_set rfds;
727     struct timeval tv;
728     int retval;
730     /* Watch stdin (fd 0) to see when it has input. */
732     FD_ZERO(&rfds);
733     FD_SET(0, &rfds);
735     /* Wait up to five seconds. */
737     tv.tv_sec = 5;
738     tv.tv_usec = 0;
740     retval = select(1, &rfds, NULL, NULL, &tv);
741     /* Don\(aqt rely on the value of tv now! */
743     if (retval == \-1)
744         perror("select()");
745     else if (retval)
746         printf("Data is available now.\en");
747         /* FD_ISSET(0, &rfds) will be true. */
748     else
749         printf("No data within five seconds.\en");
751     exit(EXIT_SUCCESS);
754 .SH SEE ALSO
755 .BR accept (2),
756 .BR connect (2),
757 .BR poll (2),
758 .BR read (2),
759 .BR recv (2),
760 .BR restart_syscall (2),
761 .BR send (2),
762 .BR sigprocmask (2),
763 .BR write (2),
764 .BR epoll (7),
765 .BR time (7)
767 For a tutorial with discussion and examples, see
768 .BR select_tut (2).