OSDN Git Service

(split) LDP: Update original to LDP v3.65
[linuxjm/LDP_man-pages.git] / original / man2 / select.2
1 .\" This manpage is copyright (C) 1992 Drew Eckhardt,
2 .\"                 copyright (C) 1995 Michael Shields.
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein.  The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\" Modified 1993-07-24 by Rik Faith <faith@cs.unc.edu>
27 .\" Modified 1995-05-18 by Jim Van Zandt <jrv@vanzandt.mv.com>
28 .\" Sun Feb 11 14:07:00 MET 1996  Martin Schulze  <joey@linux.de>
29 .\"     * layout slightly modified
30 .\"
31 .\" Modified Mon Oct 21 23:05:29 EDT 1996 by Eric S. Raymond <esr@thyrsus.com>
32 .\" Modified Thu Feb 24 01:41:09 CET 2000 by aeb
33 .\" Modified Thu Feb  9 22:32:09 CET 2001 by bert hubert <ahu@ds9a.nl>, aeb
34 .\" Modified Mon Nov 11 14:35:00 PST 2002 by Ben Woodard <ben@zork.net>
35 .\" 2005-03-11, mtk, modified pselect() text (it is now a system
36 .\"     call in 2.6.16.
37 .\"
38 .TH SELECT 2 2014-01-31 "Linux" "Linux Programmer's Manual"
39 .SH NAME
40 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
41 synchronous I/O multiplexing
42 .SH SYNOPSIS
43 .nf
44 /* According to POSIX.1-2001 */
45 .br
46 .B #include <sys/select.h>
47 .sp
48 /* According to earlier standards */
49 .br
50 .B #include <sys/time.h>
51 .br
52 .B #include <sys/types.h>
53 .br
54 .B #include <unistd.h>
55 .sp
56 .BI "int select(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
57 .BI "           fd_set *" exceptfds ", struct timeval *" timeout );
58 .sp
59 .BI "void FD_CLR(int " fd ", fd_set *" set );
60 .br
61 .BI "int  FD_ISSET(int " fd ", fd_set *" set );
62 .br
63 .BI "void FD_SET(int " fd ", fd_set *" set );
64 .br
65 .BI "void FD_ZERO(fd_set *" set );
66 .sp
67 .B #include <sys/select.h>
68 .sp
69 .BI "int pselect(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
70 .BI "            fd_set *" exceptfds ", const struct timespec *" timeout ,
71 .BI "            const sigset_t *" sigmask );
72 .fi
73 .sp
74 .in -4n
75 Feature Test Macro Requirements for glibc (see
76 .BR feature_test_macros (7)):
77 .in
78 .sp
79 .BR pselect ():
80 _POSIX_C_SOURCE\ >=\ 200112L || _XOPEN_SOURCE\ >=\ 600
81 .SH DESCRIPTION
82 .BR select ()
83 and
84 .BR pselect ()
85 allow a program to monitor multiple file descriptors,
86 waiting until one or more of the file descriptors become "ready"
87 for some class of I/O operation (e.g., input possible).
88 A file descriptor is considered ready if it is possible to
89 perform the corresponding I/O operation (e.g.,
90 .BR read (2))
91 without blocking.
92 .PP
93 The operation of
94 .BR select ()
95 and
96 .BR pselect ()
97 is identical, other than these three differences:
98 .TP
99 (i)
100 .BR select ()
101 uses a timeout that is a
102 .I struct timeval
103 (with seconds and microseconds), while
104 .BR pselect ()
105 uses a
106 .I struct timespec
107 (with seconds and nanoseconds).
108 .TP
109 (ii)
110 .BR select ()
111 may update the
112 .I timeout
113 argument to indicate how much time was left.
114 .BR pselect ()
115 does not change this argument.
116 .TP
117 (iii)
118 .BR select ()
119 has no
120 .I sigmask
121 argument, and behaves as
122 .BR pselect ()
123 called with NULL
124 .IR sigmask .
125 .PP
126 Three independent sets of file descriptors are watched.
127 Those listed in
128 .I readfds
129 will be watched to see if characters become
130 available for reading (more precisely, to see if a read will not
131 block; in particular, a file descriptor is also ready on end-of-file),
132 those in
133 .I writefds
134 will be watched to see if a write will not block, and
135 those in
136 .I exceptfds
137 will be watched for exceptions.
138 On exit, the sets are modified in place
139 to indicate which file descriptors actually changed status.
140 Each of the three file descriptor sets may be specified as NULL
141 if no file descriptors are to be watched for the corresponding class
142 of events.
143 .PP
144 Four macros are provided to manipulate the sets.
145 .BR FD_ZERO ()
146 clears a set.
147 .BR FD_SET ()
148 and
149 .BR FD_CLR ()
150 respectively add and remove a given file descriptor from a set.
151 .BR FD_ISSET ()
152 tests to see if a file descriptor is part of the set;
153 this is useful after
154 .BR select ()
155 returns.
156 .PP
157 .I nfds
158 is the highest-numbered file descriptor in any of the three sets, plus 1.
159 .PP
160 The
161 .I timeout
162 argument specifies the interval that
163 .BR select ()
164 should block waiting for a file descriptor to become ready.
165 The call will block until either:
166 .IP * 3
167 a file descriptor becomes ready;
168 .IP *
169 the call is interrupted by a signal handler; or
170 .IP *
171 the timeout expires.
172 .PP
173 Note that the
174 .I timeout
175 interval will be rounded up to the system clock granularity,
176 and kernel scheduling delays mean that the blocking interval
177 may overrun by a small amount.
178 If both fields of the
179 .I timeval
180 structure are zero, then
181 .BR select ()
182 returns immediately.
183 (This is useful for polling.)
184 If
185 .I timeout
186 is NULL (no timeout),
187 .BR select ()
188 can block indefinitely.
189 .PP
190 .I sigmask
191 is a pointer to a signal mask (see
192 .BR sigprocmask (2));
193 if it is not NULL, then
194 .BR pselect ()
195 first replaces the current signal mask by the one pointed to by
196 .IR sigmask ,
197 then does the "select" function, and then restores the original
198 signal mask.
199 .PP
200 Other than the difference in the precision of the
201 .I timeout
202 argument, the following
203 .BR pselect ()
204 call:
205 .nf
206
207     ready = pselect(nfds, &readfds, &writefds, &exceptfds,
208                     timeout, &sigmask);
209
210 .fi
211 is equivalent to
212 .I atomically
213 executing the following calls:
214 .nf
215
216     sigset_t origmask;
217
218     pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);
219     ready = select(nfds, &readfds, &writefds, &exceptfds, timeout);
220     pthread_sigmask(SIG_SETMASK, &origmask, NULL);
221 .fi
222 .PP
223 The reason that
224 .BR pselect ()
225 is needed is that if one wants to wait for either a signal
226 or for a file descriptor to become ready, then
227 an atomic test is needed to prevent race conditions.
228 (Suppose the signal handler sets a global flag and
229 returns.
230 Then a test of this global flag followed by a call of
231 .BR select ()
232 could hang indefinitely if the signal arrived just after the test
233 but just before the call.
234 By contrast,
235 .BR pselect ()
236 allows one to first block signals, handle the signals that have come in,
237 then call
238 .BR pselect ()
239 with the desired
240 .IR sigmask ,
241 avoiding the race.)
242 .SS The timeout
243 The time structures involved are defined in
244 .I <sys/time.h>
245 and look like
246
247 .in +4n
248 .nf
249 struct timeval {
250     long    tv_sec;         /* seconds */
251     long    tv_usec;        /* microseconds */
252 };
253 .fi
254 .in
255
256 and
257
258 .in +4n
259 .nf
260 struct timespec {
261     long    tv_sec;         /* seconds */
262     long    tv_nsec;        /* nanoseconds */
263 };
264 .fi
265 .in
266
267 (However, see below on the POSIX.1-2001 versions.)
268 .PP
269 Some code calls
270 .BR select ()
271 with all three sets empty,
272 .I nfds
273 zero, and a non-NULL
274 .I timeout
275 as a fairly portable way to sleep with subsecond precision.
276 .PP
277 On Linux,
278 .BR select ()
279 modifies
280 .I timeout
281 to reflect the amount of time not slept; most other implementations
282 do not do this.
283 (POSIX.1-2001 permits either behavior.)
284 This causes problems both when Linux code which reads
285 .I timeout
286 is ported to other operating systems, and when code is ported to Linux
287 that reuses a \fIstruct timeval\fP for multiple
288 .BR select ()s
289 in a loop without reinitializing it.
290 Consider
291 .I timeout
292 to be undefined after
293 .BR select ()
294 returns.
295 .\" .PP - it is rumored that:
296 .\" On BSD, when a timeout occurs, the file descriptor bits are not changed.
297 .\" - it is certainly true that:
298 .\" Linux follows SUSv2 and sets the bit masks to zero upon a timeout.
299 .SH RETURN VALUE
300 On success,
301 .BR select ()
302 and
303 .BR pselect ()
304 return the number of file descriptors contained in the three returned
305 descriptor sets (that is, the total number of bits that are set in
306 .IR readfds ,
307 .IR writefds ,
308 .IR exceptfds )
309 which may be zero if the timeout expires before anything interesting happens.
310 On error, \-1 is returned, and
311 .I errno
312 is set to indicate the error;
313 the file descriptor sets are unmodified,
314 and
315 .I timeout
316 becomes undefined.
317 .SH ERRORS
318 .TP
319 .B EBADF
320 An invalid file descriptor was given in one of the sets.
321 (Perhaps a file descriptor that was already closed,
322 or one on which an error has occurred.)
323 .TP
324 .B EINTR
325 A signal was caught; see
326 .BR signal (7).
327 .TP
328 .B EINVAL
329 .I nfds
330 is negative or the value contained within
331 .I timeout
332 is invalid.
333 .TP
334 .B ENOMEM
335 unable to allocate memory for internal tables.
336 .SH VERSIONS
337 .BR pselect ()
338 was added to Linux in kernel 2.6.16.
339 Prior to this,
340 .BR pselect ()
341 was emulated in glibc (but see BUGS).
342 .SH CONFORMING TO
343 .BR select ()
344 conforms to POSIX.1-2001 and
345 4.4BSD
346 .RB ( select ()
347 first appeared in 4.2BSD).
348 Generally portable to/from
349 non-BSD systems supporting clones of the BSD socket layer (including
350 System V variants).
351 However, note that the System V variant typically
352 sets the timeout variable before exit, but the BSD variant does not.
353 .PP
354 .BR pselect ()
355 is defined in POSIX.1g, and in
356 POSIX.1-2001.
357 .SH NOTES
358 An
359 .I fd_set
360 is a fixed size buffer.
361 Executing
362 .BR FD_CLR ()
363 or
364 .BR FD_SET ()
365 with a value of
366 .I fd
367 that is negative or is equal to or larger than
368 .B FD_SETSIZE
369 will result
370 in undefined behavior.
371 Moreover, POSIX requires
372 .I fd
373 to be a valid file descriptor.
374
375 Concerning the types involved, the classical situation is that
376 the two fields of a
377 .I timeval
378 structure are typed as
379 .I long
380 (as shown above), and the structure is defined in
381 .IR <sys/time.h> .
382 The POSIX.1-2001 situation is
383
384 .in +4n
385 .nf
386 struct timeval {
387     time_t         tv_sec;     /* seconds */
388     suseconds_t    tv_usec;    /* microseconds */
389 };
390 .fi
391 .in
392
393 where the structure is defined in
394 .I <sys/select.h>
395 and the data types
396 .I time_t
397 and
398 .I suseconds_t
399 are defined in
400 .IR <sys/types.h> .
401 .LP
402 Concerning prototypes, the classical situation is that one should
403 include
404 .I <time.h>
405 for
406 .BR select ().
407 The POSIX.1-2001 situation is that one should include
408 .I <sys/select.h>
409 for
410 .BR select ()
411 and
412 .BR pselect ().
413
414 Libc4 and libc5 do not have a
415 .I <sys/select.h>
416 header; under glibc 2.0 and later this header exists.
417 Under glibc 2.0 it unconditionally gives the wrong prototype for
418 .BR pselect ().
419 Under glibc 2.1 to 2.2.1 it gives
420 .BR pselect ()
421 when
422 .B _GNU_SOURCE
423 is defined.
424 Since glibc 2.2.2 the requirements are as shown in the SYNOPSIS.
425 .SS Multithreaded applications
426 If a file descriptor being monitored by
427 .BR select ()
428 is closed in another thread, the result is unspecified.
429 On some UNIX systems,
430 .BR select ()
431 unblocks and returns, with an indication that the file descriptor is ready
432 (a subsequent I/O operation will likely fail with an error,
433 unless another the file descriptor reopened between the time
434 .BR select ()
435 returned and the I/O operations was performed).
436 On Linux (and some other systems),
437 closing the file descriptor in another thread has no effect on
438 .BR select ().
439 In summary, any application that relies on a particular behavior
440 in this scenario must be considered buggy.
441 .SS Linux notes
442 The
443 .BR pselect ()
444 interface described in this page is implemented by glibc.
445 The underlying Linux system call is named
446 .BR pselect6 ().
447 This system call has somewhat different behavior from the glibc
448 wrapper function.
449
450 The Linux
451 .BR pselect6 ()
452 system call modifies its
453 .I timeout
454 argument.
455 However, the glibc wrapper function hides this behavior
456 by using a local variable for the timeout argument that
457 is passed to the system call.
458 Thus, the glibc
459 .BR pselect ()
460 function does not modify its
461 .I timeout
462 argument;
463 this is the behavior required by POSIX.1-2001.
464
465 The final argument of the
466 .BR pselect6 ()
467 system call is not a
468 .I "sigset_t\ *"
469 pointer, but is instead a structure of the form:
470 .in +4
471 .nf
472
473 struct {
474     const sigset_t *ss;     /* Pointer to signal set */
475     size_t          ss_len; /* Size (in bytes) of object pointed
476                                to by 'ss' */
477 };
478
479 .fi
480 .in
481 This allows the system call to obtain both
482 a pointer to the signal set and its size,
483 while allowing for the fact that most architectures
484 support a maximum of 6 arguments to a system call.
485 .SH BUGS
486 Glibc 2.0 provided a version of
487 .BR pselect ()
488 that did not take a
489 .I sigmask
490 argument.
491
492 Starting with version 2.1, glibc provided an emulation of
493 .BR pselect ()
494 that was implemented using
495 .BR sigprocmask (2)
496 and
497 .BR select ().
498 This implementation remained vulnerable to the very race condition that
499 .BR pselect ()
500 was designed to prevent.
501 Modern versions of glibc use the (race-free)
502 .BR pselect ()
503 system call on kernels where it is provided.
504
505 On systems that lack
506 .BR pselect (),
507 reliable (and more portable) signal trapping can be achieved
508 using the self-pipe trick.
509 In this technique,
510 a signal handler writes a byte to a pipe whose other end
511 is monitored by
512 .BR select ()
513 in the main program.
514 (To avoid possibly blocking when writing to a pipe that may be full
515 or reading from a pipe that may be empty,
516 nonblocking I/O is used when reading from and writing to the pipe.)
517
518 Under Linux,
519 .BR select ()
520 may report a socket file descriptor as "ready for reading", while
521 nevertheless a subsequent read blocks.
522 This could for example
523 happen when data has arrived but upon examination has wrong
524 checksum and is discarded.
525 There may be other circumstances
526 in which a file descriptor is spuriously reported as ready.
527 .\" Stevens discusses a case where accept can block after select
528 .\" returns successfully because of an intervening RST from the client.
529 Thus it may be safer to use
530 .B O_NONBLOCK
531 on sockets that should not block.
532 .\" Maybe the kernel should have returned EIO in such a situation?
533
534 On Linux,
535 .BR select ()
536 also modifies
537 .I timeout
538 if the call is interrupted by a signal handler (i.e., the
539 .B EINTR
540 error return).
541 This is not permitted by POSIX.1-2001.
542 The Linux
543 .BR pselect ()
544 system call has the same behavior,
545 but the glibc wrapper hides this behavior by internally copying the
546 .I timeout
547 to a local variable and passing that variable to the system call.
548 .SH EXAMPLE
549 .nf
550 #include <stdio.h>
551 #include <stdlib.h>
552 #include <sys/time.h>
553 #include <sys/types.h>
554 #include <unistd.h>
555
556 int
557 main(void)
558 {
559     fd_set rfds;
560     struct timeval tv;
561     int retval;
562
563     /* Watch stdin (fd 0) to see when it has input. */
564     FD_ZERO(&rfds);
565     FD_SET(0, &rfds);
566
567     /* Wait up to five seconds. */
568     tv.tv_sec = 5;
569     tv.tv_usec = 0;
570
571     retval = select(1, &rfds, NULL, NULL, &tv);
572     /* Don't rely on the value of tv now! */
573
574     if (retval == \-1)
575         perror("select()");
576     else if (retval)
577         printf("Data is available now.\\n");
578         /* FD_ISSET(0, &rfds) will be true. */
579     else
580         printf("No data within five seconds.\\n");
581
582     exit(EXIT_SUCCESS);
583 }
584 .fi
585 .SH SEE ALSO
586 .BR accept (2),
587 .BR connect (2),
588 .BR poll (2),
589 .BR read (2),
590 .BR recv (2),
591 .BR send (2),
592 .BR sigprocmask (2),
593 .BR write (2),
594 .BR epoll (7),
595 .BR time (7)
596
597 For a tutorial with discussion and examples, see
598 .BR select_tut (2).
599 .SH COLOPHON
600 This page is part of release 3.65 of the Linux
601 .I man-pages
602 project.
603 A description of the project,
604 and information about reporting bugs,
605 can be found at
606 \%http://www.kernel.org/doc/man\-pages/.