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 2019-03-06 "Linux" "Linux Programmer's Manual"
34 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
35 synchronous I/O multiplexing
44 is used to efficiently monitor multiple file descriptors,
45 to see if any of them is, or becomes, "ready";
46 that is, to see whether I/O becomes possible,
47 or an "exceptional condition" has occurred on any of the file descriptors.
49 Its principal arguments are three "sets" of file descriptors:
50 \fIreadfds\fP, \fIwritefds\fP, and \fIexceptfds\fP.
51 Each set is declared as type
53 and its contents can be manipulated with the macros
59 A newly declared set should first be cleared using
62 modifies the contents of the sets according to the rules
63 described below; after calling
65 you can test if a file descriptor is still present in a set with the
69 returns nonzero if a specified file descriptor is present in a set
70 and zero if it is not.
72 removes a file descriptor from a set.
76 This set is watched to see if data is available for reading from any of
80 has returned, \fIreadfds\fP will be
81 cleared of all file descriptors except for those that
82 are immediately available for reading.
85 This set is watched to see if there is space to write data to any of
89 has returned, \fIwritefds\fP will be
90 cleared of all file descriptors except for those that
91 are immediately available for writing.
94 This set is watched for "exceptional conditions".
95 In practice, only one such exceptional condition is common:
96 the availability of \fIout-of-band\fP (OOB) data for reading
103 for more details about OOB data.
104 (One other less common case where
106 indicates an exceptional condition occurs with pseudoterminals
112 \fIexceptfds\fP will be cleared of all file descriptors except for those
113 for which an exceptional condition has occurred.
116 This is an integer one more than the maximum of any file descriptor in
118 In other words, while adding file descriptors to each of the sets,
119 you must calculate the maximum integer value of all of them,
120 then increment this value by one, and then pass this as \fInfds\fP.
123 This is the longest time
125 may wait before returning, even if nothing interesting happened.
126 If this value is passed as NULL, then
128 blocks indefinitely waiting for a file descriptor to become ready.
129 \fIutimeout\fP can be set to zero seconds, which causes
131 to return immediately, with information about the readiness
132 of file descriptors at the time of the call.
133 The structure \fIstruct timeval\fP is defined as:
138 time_t tv_sec; /* seconds */
139 long tv_usec; /* microseconds */
147 has the same meaning as
151 has nanosecond precision as follows:
156 long tv_sec; /* seconds */
157 long tv_nsec; /* nanoseconds */
163 This argument holds a set of signals that the kernel should unblock
164 (i.e., remove from the signal mask of the calling thread),
165 while the caller is blocked inside the
170 .BR sigprocmask (2)).
172 in which case the call does not modify the signal mask on
173 entry and exit to the function.
176 will then behave just like
178 .SS Combining signal and data events
180 is useful if you are waiting for a signal as well as
181 for file descriptor(s) to become ready for I/O.
182 Programs that receive signals
183 normally use the signal handler only to raise a global flag.
184 The global flag will indicate that the event must be processed
185 in the main loop of the program.
186 A signal will cause the
190 call to return with \fIerrno\fP set to \fBEINTR\fP.
191 This behavior is essential so that signals can be processed
192 in the main loop of the program, otherwise
194 would block indefinitely.
196 in the main loop will be a conditional to check the global flag.
198 what if a signal arrives after the conditional, but before the
203 would block indefinitely, even though an event is actually pending.
204 This race condition is solved by the
207 This call can be used to set the signal mask to a set of signals
208 that are to be received only within the
211 For instance, let us say that the event in question
212 was the exit of a child process.
213 Before the start of the main loop, we
214 would block \fBSIGCHLD\fP using
220 by using an empty signal mask.
221 Our program would look like:
224 static volatile sig_atomic_t got_SIGCHLD = 0;
227 child_sig_handler(int sig)
233 main(int argc, char *argv[])
235 sigset_t sigmask, empty_mask;
237 fd_set readfds, writefds, exceptfds;
240 sigemptyset(&sigmask);
241 sigaddset(&sigmask, SIGCHLD);
242 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
243 perror("sigprocmask");
248 sa.sa_handler = child_sig_handler;
249 sigemptyset(&sa.sa_mask);
250 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
255 sigemptyset(&empty_mask);
257 for (;;) { /* main loop */
258 /* Initialize readfds, writefds, and exceptfds
259 before the pselect() call. (Code omitted.) */
261 r = pselect(nfds, &readfds, &writefds, &exceptfds,
263 if (r == \-1 && errno != EINTR) {
270 /* Handle signalled event here; e.g., wait() for all
271 terminated children. (Code omitted.) */
274 /* main body of program */
279 So what is the point of
281 Can't I just read and write to my file descriptors whenever I want?
285 multiple descriptors at the same time and properly puts the process to
286 sleep if there is no activity.
287 UNIX programmers often find
288 themselves in a position where they have to handle I/O from more than one
289 file descriptor where the data flow may be intermittent.
290 If you were to merely create a sequence of
295 find that one of your calls may block waiting for data from/to a file
296 descriptor, while another file descriptor is unused though ready for I/O.
298 efficiently copes with this situation.
300 Many people who try to use
302 come across behavior that is
303 difficult to understand and produces nonportable or borderline results.
304 For instance, the above program is carefully written not to
305 block at any point, even though it does not set its file descriptors to
307 It is easy to introduce
308 subtle errors that will remove the advantage of using
310 so here is a list of essentials to watch for when using
314 You should always try to use
318 should have nothing to do if there is no data available.
320 depends on timeouts is not usually portable and is difficult to debug.
323 The value \fInfds\fP must be properly calculated for efficiency as
327 No file descriptor must be added to any set if you do not intend
328 to check its result after the
330 call, and respond appropriately.
336 returns, all file descriptors in all sets
337 should be checked to see if they are ready.
346 do \fInot\fP necessarily read/write the full amount of data
347 that you have requested.
348 If they do read/write the full amount, it's
349 because you have a low traffic load and a fast stream.
350 This is not always going to be the case.
351 You should cope with the case of your
352 functions managing to send or receive only a single byte.
355 Never read/write only in single bytes at a time unless you are really
356 sure that you have a small amount of data to process.
358 inefficient not to read/write as much data as you can buffer each time.
359 The buffers in the example below are 1024 bytes although they could
360 easily be made larger.
370 can fail with the error
380 set to \fBEAGAIN\fP (\fBEWOULDBLOCK\fP).
381 These results must be properly managed (not done properly above).
382 If your program is not going to receive any signals, then
383 it is unlikely you will get \fBEINTR\fP.
384 If your program does not set nonblocking I/O,
385 you will not get \fBEAGAIN\fP.
386 .\" Nonetheless, you should still cope with these errors for completeness.
395 with a buffer length of zero.
404 fail with errors other than those listed in \fB7.\fP,
405 or one of the input functions returns 0, indicating end of file,
406 then you should \fInot\fP pass that file descriptor to
409 In the example below,
410 I close the file descriptor immediately, and then set it to \-1
411 to prevent it being included in a set.
414 The timeout value must be initialized with each new call to
416 since some operating systems modify the structure.
418 however does not modify its timeout structure.
423 modifies its file descriptor sets,
424 if the call is being used in a loop,
425 then the sets must be reinitialized before each call.
426 .\" "I have heard" does not fill me with confidence, and doesn't
427 .\" belong in a man page, so I've commented this point out.
430 .\" I have heard that the Windows socket layer does not cope with OOB data
432 .\" It also does not cope with
434 .\" calls when no file descriptors are set at all.
435 .\" Having no file descriptors set is a useful
436 .\" way to sleep the process with subsecond precision by using the timeout.
437 .\" (See further on.)
441 returns the total number of file descriptors
442 still present in the file descriptor sets.
446 timed out, then the return value will be zero.
447 The file descriptors set should be all
448 empty (but may not be on some systems).
450 A return value of \-1 indicates an error, with \fIerrno\fP being
452 In the case of an error, the contents of the returned sets and
453 the \fIstruct timeout\fP contents are undefined and should not be used.
455 however never modifies \fIntimeout\fP.
458 all operating systems that support sockets also support
462 many problems in a portable and efficient way that naive programmers try
463 to solve in a more complicated manner using
464 threads, forking, IPCs, signals, memory sharing, and so on.
468 system call has the same functionality as
470 and is somewhat more efficient when monitoring sparse
471 file descriptor sets.
472 It is nowadays widely available, but historically was less portable than
477 API provides an interface that is more efficient than
481 when monitoring large numbers of file descriptors.
483 Here is an example that better demonstrates the true utility of
485 The listing below is a TCP forwarding program that forwards
486 from one TCP port to another.
492 #include <sys/time.h>
493 #include <sys/types.h>
496 #include <sys/socket.h>
497 #include <netinet/in.h>
498 #include <arpa/inet.h>
501 static int forward_port;
504 #define max(x,y) ((x) > (y) ? (x) : (y))
507 listen_socket(int listen_port)
509 struct sockaddr_in addr;
513 lfd = socket(AF_INET, SOCK_STREAM, 0);
520 if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR,
521 &yes, sizeof(yes)) == \-1) {
522 perror("setsockopt");
527 memset(&addr, 0, sizeof(addr));
528 addr.sin_port = htons(listen_port);
529 addr.sin_family = AF_INET;
530 if (bind(lfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
536 printf("accepting connections on port %d\en", listen_port);
542 connect_socket(int connect_port, char *address)
544 struct sockaddr_in addr;
547 cfd = socket(AF_INET, SOCK_STREAM, 0);
553 memset(&addr, 0, sizeof(addr));
554 addr.sin_port = htons(connect_port);
555 addr.sin_family = AF_INET;
557 if (!inet_aton(address, (struct in_addr *) &addr.sin_addr.s_addr)) {
558 fprintf(stderr, "inet_aton(): bad IP address format\en");
563 if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
565 shutdown(cfd, SHUT_RDWR);
572 #define SHUT_FD1 do { \e
574 shutdown(fd1, SHUT_RDWR); \e
580 #define SHUT_FD2 do { \e
582 shutdown(fd2, SHUT_RDWR); \e
588 #define BUF_SIZE 1024
591 main(int argc, char *argv[])
594 int fd1 = \-1, fd2 = \-1;
595 char buf1[BUF_SIZE], buf2[BUF_SIZE];
596 int buf1_avail = 0, buf1_written = 0;
597 int buf2_avail = 0, buf2_written = 0;
600 fprintf(stderr, "Usage\en\etfwd <listen\-port> "
601 "<forward\-to\-port> <forward\-to\-ip\-address>\en");
605 signal(SIGPIPE, SIG_IGN);
607 forward_port = atoi(argv[2]);
609 h = listen_socket(atoi(argv[1]));
616 fd_set readfds, writefds, exceptfds;
624 if (fd1 > 0 && buf1_avail < BUF_SIZE)
625 FD_SET(fd1, &readfds);
626 /* Note: nfds is updated below, when fd1 is added to
628 if (fd2 > 0 && buf2_avail < BUF_SIZE)
629 FD_SET(fd2, &readfds);
631 if (fd1 > 0 && buf2_avail \- buf2_written > 0)
632 FD_SET(fd1, &writefds);
633 if (fd2 > 0 && buf1_avail \- buf1_written > 0)
634 FD_SET(fd2, &writefds);
637 FD_SET(fd1, &exceptfds);
638 nfds = max(nfds, fd1);
641 FD_SET(fd2, &exceptfds);
642 nfds = max(nfds, fd2);
645 ready = select(nfds + 1, &readfds, &writefds, &exceptfds, NULL);
647 if (ready == \-1 && errno == EINTR)
655 if (FD_ISSET(h, &readfds)) {
657 struct sockaddr_in client_addr;
660 addrlen = sizeof(client_addr);
661 memset(&client_addr, 0, addrlen);
662 fd = accept(h, (struct sockaddr *) &client_addr, &addrlen);
668 buf1_avail = buf1_written = 0;
669 buf2_avail = buf2_written = 0;
671 fd2 = connect_socket(forward_port, argv[3]);
675 printf("connect from %s\en",
676 inet_ntoa(client_addr.sin_addr));
678 /* Skip any events on the old, closed file descriptors. */
683 /* NB: read OOB data before normal reads */
685 if (fd1 > 0 && FD_ISSET(fd1, &exceptfds)) {
688 nbytes = recv(fd1, &c, 1, MSG_OOB);
692 send(fd2, &c, 1, MSG_OOB);
694 if (fd2 > 0 && FD_ISSET(fd2, &exceptfds)) {
697 nbytes = recv(fd2, &c, 1, MSG_OOB);
701 send(fd1, &c, 1, MSG_OOB);
703 if (fd1 > 0 && FD_ISSET(fd1, &readfds)) {
704 nbytes = read(fd1, buf1 + buf1_avail,
705 BUF_SIZE \- buf1_avail);
709 buf1_avail += nbytes;
711 if (fd2 > 0 && FD_ISSET(fd2, &readfds)) {
712 nbytes = read(fd2, buf2 + buf2_avail,
713 BUF_SIZE \- buf2_avail);
717 buf2_avail += nbytes;
719 if (fd1 > 0 && FD_ISSET(fd1, &writefds) && buf2_avail > 0) {
720 nbytes = write(fd1, buf2 + buf2_written,
721 buf2_avail \- buf2_written);
725 buf2_written += nbytes;
727 if (fd2 > 0 && FD_ISSET(fd2, &writefds) && buf1_avail > 0) {
728 nbytes = write(fd2, buf1 + buf1_written,
729 buf1_avail \- buf1_written);
733 buf1_written += nbytes;
736 /* Check if write data has caught read data */
738 if (buf1_written == buf1_avail)
739 buf1_written = buf1_avail = 0;
740 if (buf2_written == buf2_avail)
741 buf2_written = buf2_avail = 0;
743 /* One side has closed the connection, keep
744 writing to the other side until empty */
746 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
748 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
755 The above program properly forwards most kinds of TCP connections
756 including OOB signal data transmitted by \fBtelnet\fP servers.
757 It handles the tricky problem of having data flow in both directions
759 You might think it more efficient to use a
761 call and devote a thread to each stream.
762 This becomes more tricky than you might suspect.
763 Another idea is to set nonblocking I/O using
765 This also has its problems because you end up using
766 inefficient timeouts.
768 The program does not handle more than one simultaneous connection at a
769 time, although it could easily be extended to do this with a linked list
770 of buffers\(emone for each connection.
772 connections cause the current connection to be dropped.
791 .\" This man page was written by Paul Sheer.