1 .\" This manpage is copyright (C) 2001 Paul Sheer.
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
25 .\" very minor changes, aeb
27 .\" Modified 5 June 2002, Michael Kerrisk <mtk.manpages@gmail.com>
28 .\" 2006-05-13, mtk, removed much material that is redundant with select.2
29 .\" various other changes
30 .\" 2008-01-26, mtk, substantial changes and rewrites
32 .TH SELECT_TUT 2 2017-05-03 "Linux" "Linux Programmer's Manual"
34 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
35 synchronous I/O multiplexing
38 /* According to POSIX.1-2001, POSIX.1-2008 */
39 .B #include <sys/select.h>
41 /* According to earlier standards */
42 .B #include <sys/time.h>
43 .B #include <sys/types.h>
44 .B #include <unistd.h>
46 .BI "int select(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
47 .BI " fd_set *" exceptfds ", struct timeval *" utimeout );
49 .BI "void FD_CLR(int " fd ", fd_set *" set );
50 .BI "int FD_ISSET(int " fd ", fd_set *" set );
51 .BI "void FD_SET(int " fd ", fd_set *" set );
52 .BI "void FD_ZERO(fd_set *" set );
54 .B #include <sys/select.h>
56 .BI "int pselect(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
57 .BI " fd_set *" exceptfds ", const struct timespec *" ntimeout ,
58 .BI " const sigset_t *" sigmask );
62 Feature Test Macro Requirements for glibc (see
63 .BR feature_test_macros (7)):
67 _POSIX_C_SOURCE\ >=\ 200112L
72 is used to efficiently monitor multiple file descriptors,
73 to see if any of them is, or becomes, "ready";
74 that is, to see whether I/O becomes possible,
75 or an "exceptional condition" has occurred on any of the file descriptors.
77 Its principal arguments are three "sets" of file descriptors:
78 \fIreadfds\fP, \fIwritefds\fP, and \fIexceptfds\fP.
79 Each set is declared as type
81 and its contents can be manipulated with the macros
87 A newly declared set should first be cleared using
90 modifies the contents of the sets according to the rules
91 described below; after calling
93 you can test if a file descriptor is still present in a set with the
97 returns nonzero if a specified file descriptor is present in a set
98 and zero if it is not.
100 removes a file descriptor from a set.
104 This set is watched to see if data is available for reading from any of
105 its file descriptors.
108 has returned, \fIreadfds\fP will be
109 cleared of all file descriptors except for those that
110 are immediately available for reading.
113 This set is watched to see if there is space to write data to any of
114 its file descriptors.
117 has returned, \fIwritefds\fP will be
118 cleared of all file descriptors except for those that
119 are immediately available for writing.
122 This set is watched for "exceptional conditions".
123 In practice, only one such exceptional condition is common:
124 the availability of \fIout-of-band\fP (OOB) data for reading
131 for more details about OOB data.
132 (One other less common case where
134 indicates an exceptional condition occurs with pseudoterminals
140 \fIexceptfds\fP will be cleared of all file descriptors except for those
141 for which an exceptional condition has occurred.
144 This is an integer one more than the maximum of any file descriptor in
146 In other words, while adding file descriptors to each of the sets,
147 you must calculate the maximum integer value of all of them,
148 then increment this value by one, and then pass this as \fInfds\fP.
151 This is the longest time
153 may wait before returning, even if nothing interesting happened.
154 If this value is passed as NULL, then
156 blocks indefinitely waiting for a file descriptor to become ready.
157 \fIutimeout\fP can be set to zero seconds, which causes
159 to return immediately, with information about the readiness
160 of file descriptors at the time of the call.
161 The structure \fIstruct timeval\fP is defined as:
166 time_t tv_sec; /* seconds */
167 long tv_usec; /* microseconds */
175 has the same meaning as
179 has nanosecond precision as follows:
184 long tv_sec; /* seconds */
185 long tv_nsec; /* nanoseconds */
191 This argument holds a set of signals that the kernel should unblock
192 (i.e., remove from the signal mask of the calling thread),
193 while the caller is blocked inside the
198 .BR sigprocmask (2)).
200 in which case the call does not modify the signal mask on
201 entry and exit to the function.
204 will then behave just like
206 .SS Combining signal and data events
208 is useful if you are waiting for a signal as well as
209 for file descriptor(s) to become ready for I/O.
210 Programs that receive signals
211 normally use the signal handler only to raise a global flag.
212 The global flag will indicate that the event must be processed
213 in the main loop of the program.
214 A signal will cause the
218 call to return with \fIerrno\fP set to \fBEINTR\fP.
219 This behavior is essential so that signals can be processed
220 in the main loop of the program, otherwise
222 would block indefinitely.
224 in the main loop will be a conditional to check the global flag.
226 what if a signal arrives after the conditional, but before the
231 would block indefinitely, even though an event is actually pending.
232 This race condition is solved by the
235 This call can be used to set the signal mask to a set of signals
236 that are to be received only within the
239 For instance, let us say that the event in question
240 was the exit of a child process.
241 Before the start of the main loop, we
242 would block \fBSIGCHLD\fP using
248 by using an empty signal mask.
249 Our program would look like:
252 static volatile sig_atomic_t got_SIGCHLD = 0;
255 child_sig_handler(int sig)
261 main(int argc, char *argv[])
263 sigset_t sigmask, empty_mask;
265 fd_set readfds, writefds, exceptfds;
268 sigemptyset(&sigmask);
269 sigaddset(&sigmask, SIGCHLD);
270 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
271 perror("sigprocmask");
276 sa.sa_handler = child_sig_handler;
277 sigemptyset(&sa.sa_mask);
278 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
283 sigemptyset(&empty_mask);
285 for (;;) { /* main loop */
286 /* Initialize readfds, writefds, and exceptfds
287 before the pselect() call. (Code omitted.) */
289 r = pselect(nfds, &readfds, &writefds, &exceptfds,
291 if (r == \-1 && errno != EINTR) {
298 /* Handle signalled event here; e.g., wait() for all
299 terminated children. (Code omitted.) */
302 /* main body of program */
307 So what is the point of
309 Can't I just read and write to my file descriptors whenever I want?
313 multiple descriptors at the same time and properly puts the process to
314 sleep if there is no activity.
315 UNIX programmers often find
316 themselves in a position where they have to handle I/O from more than one
317 file descriptor where the data flow may be intermittent.
318 If you were to merely create a sequence of
323 find that one of your calls may block waiting for data from/to a file
324 descriptor, while another file descriptor is unused though ready for I/O.
326 efficiently copes with this situation.
328 Many people who try to use
330 come across behavior that is
331 difficult to understand and produces nonportable or borderline results.
332 For instance, the above program is carefully written not to
333 block at any point, even though it does not set its file descriptors to
335 It is easy to introduce
336 subtle errors that will remove the advantage of using
338 so here is a list of essentials to watch for when using
342 You should always try to use
346 should have nothing to do if there is no data available.
348 depends on timeouts is not usually portable and is difficult to debug.
351 The value \fInfds\fP must be properly calculated for efficiency as
355 No file descriptor must be added to any set if you do not intend
356 to check its result after the
358 call, and respond appropriately.
364 returns, all file descriptors in all sets
365 should be checked to see if they are ready.
374 do \fInot\fP necessarily read/write the full amount of data
375 that you have requested.
376 If they do read/write the full amount, it's
377 because you have a low traffic load and a fast stream.
378 This is not always going to be the case.
379 You should cope with the case of your
380 functions managing to send or receive only a single byte.
383 Never read/write only in single bytes at a time unless you are really
384 sure that you have a small amount of data to process.
386 inefficient not to read/write as much data as you can buffer each time.
387 The buffers in the example below are 1024 bytes although they could
388 easily be made larger.
398 can fail with the error
408 set to \fBEAGAIN\fP (\fBEWOULDBLOCK\fP).
409 These results must be properly managed (not done properly above).
410 If your program is not going to receive any signals, then
411 it is unlikely you will get \fBEINTR\fP.
412 If your program does not set nonblocking I/O,
413 you will not get \fBEAGAIN\fP.
414 .\" Nonetheless, you should still cope with these errors for completeness.
423 with a buffer length of zero.
432 fail with errors other than those listed in \fB7.\fP,
433 or one of the input functions returns 0, indicating end of file,
434 then you should \fInot\fP pass that file descriptor to
437 In the example below,
438 I close the file descriptor immediately, and then set it to \-1
439 to prevent it being included in a set.
442 The timeout value must be initialized with each new call to
444 since some operating systems modify the structure.
446 however does not modify its timeout structure.
451 modifies its file descriptor sets,
452 if the call is being used in a loop,
453 then the sets must be reinitialized before each call.
454 .\" "I have heard" does not fill me with confidence, and doesn't
455 .\" belong in a man page, so I've commented this point out.
458 .\" I have heard that the Windows socket layer does not cope with OOB data
460 .\" It also does not cope with
462 .\" calls when no file descriptors are set at all.
463 .\" Having no file descriptors set is a useful
464 .\" way to sleep the process with subsecond precision by using the timeout.
465 .\" (See further on.)
467 On systems that do not have a
469 function, you can call
471 with a finite timeout and no file descriptors as
478 tv.tv_usec = 200000; /* 0.2 seconds */
479 select(0, NULL, NULL, NULL, &tv);
483 This is guaranteed to work only on UNIX systems, however.
487 returns the total number of file descriptors
488 still present in the file descriptor sets.
492 timed out, then the return value will be zero.
493 The file descriptors set should be all
494 empty (but may not be on some systems).
496 A return value of \-1 indicates an error, with \fIerrno\fP being
498 In the case of an error, the contents of the returned sets and
499 the \fIstruct timeout\fP contents are undefined and should not be used.
501 however never modifies \fIntimeout\fP.
504 all operating systems that support sockets also support
508 many problems in a portable and efficient way that naive programmers try
509 to solve in a more complicated manner using
510 threads, forking, IPCs, signals, memory sharing, and so on.
514 system call has the same functionality as
516 and is somewhat more efficient when monitoring sparse
517 file descriptor sets.
518 It is nowadays widely available, but historically was less portable than
523 API provides an interface that is more efficient than
527 when monitoring large numbers of file descriptors.
529 Here is an example that better demonstrates the true utility of
531 The listing below is a TCP forwarding program that forwards
532 from one TCP port to another.
538 #include <sys/time.h>
539 #include <sys/types.h>
542 #include <sys/socket.h>
543 #include <netinet/in.h>
544 #include <arpa/inet.h>
547 static int forward_port;
550 #define max(x,y) ((x) > (y) ? (x) : (y))
553 listen_socket(int listen_port)
555 struct sockaddr_in addr;
559 lfd = socket(AF_INET, SOCK_STREAM, 0);
566 if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR,
567 &yes, sizeof(yes)) == \-1) {
568 perror("setsockopt");
573 memset(&addr, 0, sizeof(addr));
574 addr.sin_port = htons(listen_port);
575 addr.sin_family = AF_INET;
576 if (bind(lfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
582 printf("accepting connections on port %d\\n", listen_port);
588 connect_socket(int connect_port, char *address)
590 struct sockaddr_in addr;
593 cfd = socket(AF_INET, SOCK_STREAM, 0);
599 memset(&addr, 0, sizeof(addr));
600 addr.sin_port = htons(connect_port);
601 addr.sin_family = AF_INET;
603 if (!inet_aton(address, (struct in_addr *) &addr.sin_addr.s_addr)) {
604 perror("bad IP address format");
609 if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
611 shutdown(cfd, SHUT_RDWR);
618 #define SHUT_FD1 do { \\
620 shutdown(fd1, SHUT_RDWR); \\
626 #define SHUT_FD2 do { \\
628 shutdown(fd2, SHUT_RDWR); \\
634 #define BUF_SIZE 1024
637 main(int argc, char *argv[])
640 int fd1 = \-1, fd2 = \-1;
641 char buf1[BUF_SIZE], buf2[BUF_SIZE];
642 int buf1_avail = 0, buf1_written = 0;
643 int buf2_avail = 0, buf2_written = 0;
646 fprintf(stderr, "Usage\\n\\tfwd <listen\-port> "
647 "<forward\-to\-port> <forward\-to\-ip\-address>\\n");
651 signal(SIGPIPE, SIG_IGN);
653 forward_port = atoi(argv[2]);
655 h = listen_socket(atoi(argv[1]));
662 fd_set readfds, writefds, exceptfds;
670 if (fd1 > 0 && buf1_avail < BUF_SIZE)
671 FD_SET(fd1, &readfds);
672 /* Note: nfds is updated below, when fd1 is added to
674 if (fd2 > 0 && buf2_avail < BUF_SIZE)
675 FD_SET(fd2, &readfds);
677 if (fd1 > 0 && buf2_avail \- buf2_written > 0)
678 FD_SET(fd1, &writefds);
679 if (fd2 > 0 && buf1_avail \- buf1_written > 0)
680 FD_SET(fd2, &writefds);
683 FD_SET(fd1, &exceptfds);
684 nfds = max(nfds, fd1);
687 FD_SET(fd2, &exceptfds);
688 nfds = max(nfds, fd2);
691 ready = select(nfds + 1, &readfds, &writefds, &exceptfds, NULL);
693 if (ready == \-1 && errno == EINTR)
701 if (FD_ISSET(h, &readfds)) {
703 struct sockaddr_in client_addr;
706 addrlen = sizeof(client_addr);
707 memset(&client_addr, 0, addrlen);
708 fd = accept(h, (struct sockaddr *) &client_addr, &addrlen);
714 buf1_avail = buf1_written = 0;
715 buf2_avail = buf2_written = 0;
717 fd2 = connect_socket(forward_port, argv[3]);
721 printf("connect from %s\\n",
722 inet_ntoa(client_addr.sin_addr));
724 /* Skip any events on the old, closed file descriptors. */
729 /* NB: read OOB data before normal reads */
731 if (fd1 > 0 && FD_ISSET(fd1, &exceptfds)) {
734 nbytes = recv(fd1, &c, 1, MSG_OOB);
738 send(fd2, &c, 1, MSG_OOB);
740 if (fd2 > 0 && FD_ISSET(fd2, &exceptfds)) {
743 nbytes = recv(fd2, &c, 1, MSG_OOB);
747 send(fd1, &c, 1, MSG_OOB);
749 if (fd1 > 0 && FD_ISSET(fd1, &readfds)) {
750 nbytes = read(fd1, buf1 + buf1_avail,
751 BUF_SIZE \- buf1_avail);
755 buf1_avail += nbytes;
757 if (fd2 > 0 && FD_ISSET(fd2, &readfds)) {
758 nbytes = read(fd2, buf2 + buf2_avail,
759 BUF_SIZE \- buf2_avail);
763 buf2_avail += nbytes;
765 if (fd1 > 0 && FD_ISSET(fd1, &writefds) && buf2_avail > 0) {
766 nbytes = write(fd1, buf2 + buf2_written,
767 buf2_avail \- buf2_written);
771 buf2_written += nbytes;
773 if (fd2 > 0 && FD_ISSET(fd2, &writefds) && buf1_avail > 0) {
774 nbytes = write(fd2, buf1 + buf1_written,
775 buf1_avail \- buf1_written);
779 buf1_written += nbytes;
782 /* Check if write data has caught read data */
784 if (buf1_written == buf1_avail)
785 buf1_written = buf1_avail = 0;
786 if (buf2_written == buf2_avail)
787 buf2_written = buf2_avail = 0;
789 /* One side has closed the connection, keep
790 writing to the other side until empty */
792 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
794 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
801 The above program properly forwards most kinds of TCP connections
802 including OOB signal data transmitted by \fBtelnet\fP servers.
803 It handles the tricky problem of having data flow in both directions
805 You might think it more efficient to use a
807 call and devote a thread to each stream.
808 This becomes more tricky than you might suspect.
809 Another idea is to set nonblocking I/O using
811 This also has its problems because you end up using
812 inefficient timeouts.
814 The program does not handle more than one simultaneous connection at a
815 time, although it could easily be extended to do this with a linked list
816 of buffers\(emone for each connection.
818 connections cause the current connection to be dropped.
837 .\" This man page was written by Paul Sheer.