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 );
51 .BI "int FD_ISSET(int " fd ", fd_set *" set );
53 .BI "void FD_SET(int " fd ", fd_set *" set );
55 .BI "void FD_ZERO(fd_set *" set );
57 .B #include <sys/select.h>
59 .BI "int pselect(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
60 .BI " fd_set *" exceptfds ", const struct timespec *" ntimeout ,
61 .BI " const sigset_t *" sigmask );
65 Feature Test Macro Requirements for glibc (see
66 .BR feature_test_macros (7)):
70 _POSIX_C_SOURCE\ >=\ 200112L
75 is used to efficiently monitor multiple file descriptors,
76 to see if any of them is, or becomes, "ready";
77 that is, to see whether I/O becomes possible,
78 or an "exceptional condition" has occurred on any of the file descriptors.
80 Its principal arguments are three "sets" of file descriptors:
81 \fIreadfds\fP, \fIwritefds\fP, and \fIexceptfds\fP.
82 Each set is declared as type
84 and its contents can be manipulated with the macros
90 A newly declared set should first be cleared using
93 modifies the contents of the sets according to the rules
94 described below; after calling
96 you can test if a file descriptor is still present in a set with the
100 returns nonzero if a specified file descriptor is present in a set
101 and zero if it is not.
103 removes a file descriptor from a set.
107 This set is watched to see if data is available for reading from any of
108 its file descriptors.
111 has returned, \fIreadfds\fP will be
112 cleared of all file descriptors except for those that
113 are immediately available for reading.
116 This set is watched to see if there is space to write data to any of
117 its file descriptors.
120 has returned, \fIwritefds\fP will be
121 cleared of all file descriptors except for those that
122 are immediately available for writing.
125 This set is watched for "exceptional conditions".
126 In practice, only one such exceptional condition is common:
127 the availability of \fIout-of-band\fP (OOB) data for reading
134 for more details about OOB data.
135 (One other less common case where
137 indicates an exceptional condition occurs with pseudoterminals
143 \fIexceptfds\fP will be cleared of all file descriptors except for those
144 for which an exceptional condition has occurred.
147 This is an integer one more than the maximum of any file descriptor in
149 In other words, while adding file descriptors to each of the sets,
150 you must calculate the maximum integer value of all of them,
151 then increment this value by one, and then pass this as \fInfds\fP.
154 This is the longest time
156 may wait before returning, even if nothing interesting happened.
157 If this value is passed as NULL, then
159 blocks indefinitely waiting for a file descriptor to become ready.
160 \fIutimeout\fP can be set to zero seconds, which causes
162 to return immediately, with information about the readiness
163 of file descriptors at the time of the call.
164 The structure \fIstruct timeval\fP is defined as:
169 time_t tv_sec; /* seconds */
170 long tv_usec; /* microseconds */
178 has the same meaning as
182 has nanosecond precision as follows:
187 long tv_sec; /* seconds */
188 long tv_nsec; /* nanoseconds */
194 This argument holds a set of signals that the kernel should unblock
195 (i.e., remove from the signal mask of the calling thread),
196 while the caller is blocked inside the
201 .BR sigprocmask (2)).
203 in which case the call does not modify the signal mask on
204 entry and exit to the function.
207 will then behave just like
209 .SS Combining signal and data events
211 is useful if you are waiting for a signal as well as
212 for file descriptor(s) to become ready for I/O.
213 Programs that receive signals
214 normally use the signal handler only to raise a global flag.
215 The global flag will indicate that the event must be processed
216 in the main loop of the program.
217 A signal will cause the
221 call to return with \fIerrno\fP set to \fBEINTR\fP.
222 This behavior is essential so that signals can be processed
223 in the main loop of the program, otherwise
225 would block indefinitely.
227 in the main loop will be a conditional to check the global flag.
229 what if a signal arrives after the conditional, but before the
234 would block indefinitely, even though an event is actually pending.
235 This race condition is solved by the
238 This call can be used to set the signal mask to a set of signals
239 that are to be received only within the
242 For instance, let us say that the event in question
243 was the exit of a child process.
244 Before the start of the main loop, we
245 would block \fBSIGCHLD\fP using
251 by using an empty signal mask.
252 Our program would look like:
255 static volatile sig_atomic_t got_SIGCHLD = 0;
258 child_sig_handler(int sig)
264 main(int argc, char *argv[])
266 sigset_t sigmask, empty_mask;
268 fd_set readfds, writefds, exceptfds;
271 sigemptyset(&sigmask);
272 sigaddset(&sigmask, SIGCHLD);
273 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
274 perror("sigprocmask");
279 sa.sa_handler = child_sig_handler;
280 sigemptyset(&sa.sa_mask);
281 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
286 sigemptyset(&empty_mask);
288 for (;;) { /* main loop */
289 /* Initialize readfds, writefds, and exceptfds
290 before the pselect() call. (Code omitted.) */
292 r = pselect(nfds, &readfds, &writefds, &exceptfds,
294 if (r == \-1 && errno != EINTR) {
301 /* Handle signalled event here; e.g., wait() for all
302 terminated children. (Code omitted.) */
305 /* main body of program */
310 So what is the point of
312 Can't I just read and write to my file descriptors whenever I want?
316 multiple descriptors at the same time and properly puts the process to
317 sleep if there is no activity.
318 UNIX programmers often find
319 themselves in a position where they have to handle I/O from more than one
320 file descriptor where the data flow may be intermittent.
321 If you were to merely create a sequence of
326 find that one of your calls may block waiting for data from/to a file
327 descriptor, while another file descriptor is unused though ready for I/O.
329 efficiently copes with this situation.
331 Many people who try to use
333 come across behavior that is
334 difficult to understand and produces nonportable or borderline results.
335 For instance, the above program is carefully written not to
336 block at any point, even though it does not set its file descriptors to
338 It is easy to introduce
339 subtle errors that will remove the advantage of using
341 so here is a list of essentials to watch for when using
345 You should always try to use
349 should have nothing to do if there is no data available.
351 depends on timeouts is not usually portable and is difficult to debug.
354 The value \fInfds\fP must be properly calculated for efficiency as
358 No file descriptor must be added to any set if you do not intend
359 to check its result after the
361 call, and respond appropriately.
367 returns, all file descriptors in all sets
368 should be checked to see if they are ready.
377 do \fInot\fP necessarily read/write the full amount of data
378 that you have requested.
379 If they do read/write the full amount, it's
380 because you have a low traffic load and a fast stream.
381 This is not always going to be the case.
382 You should cope with the case of your
383 functions managing to send or receive only a single byte.
386 Never read/write only in single bytes at a time unless you are really
387 sure that you have a small amount of data to process.
389 inefficient not to read/write as much data as you can buffer each time.
390 The buffers in the example below are 1024 bytes although they could
391 easily be made larger.
401 can fail with the error
411 set to \fBEAGAIN\fP (\fBEWOULDBLOCK\fP).
412 These results must be properly managed (not done properly above).
413 If your program is not going to receive any signals, then
414 it is unlikely you will get \fBEINTR\fP.
415 If your program does not set nonblocking I/O,
416 you will not get \fBEAGAIN\fP.
417 .\" Nonetheless, you should still cope with these errors for completeness.
426 with a buffer length of zero.
435 fail with errors other than those listed in \fB7.\fP,
436 or one of the input functions returns 0, indicating end of file,
437 then you should \fInot\fP pass that file descriptor to
440 In the example below,
441 I close the file descriptor immediately, and then set it to \-1
442 to prevent it being included in a set.
445 The timeout value must be initialized with each new call to
447 since some operating systems modify the structure.
449 however does not modify its timeout structure.
454 modifies its file descriptor sets,
455 if the call is being used in a loop,
456 then the sets must be reinitialized before each call.
457 .\" "I have heard" does not fill me with confidence, and doesn't
458 .\" belong in a man page, so I've commented this point out.
461 .\" I have heard that the Windows socket layer does not cope with OOB data
463 .\" It also does not cope with
465 .\" calls when no file descriptors are set at all.
466 .\" Having no file descriptors set is a useful
467 .\" way to sleep the process with subsecond precision by using the timeout.
468 .\" (See further on.)
470 On systems that do not have a
472 function, you can call
474 with a finite timeout and no file descriptors as
480 tv.tv_usec = 200000; /* 0.2 seconds */
481 select(0, NULL, NULL, NULL, &tv);
484 This is guaranteed to work only on UNIX systems, however.
488 returns the total number of file descriptors
489 still present in the file descriptor sets.
493 timed out, then the return value will be zero.
494 The file descriptors set should be all
495 empty (but may not be on some systems).
497 A return value of \-1 indicates an error, with \fIerrno\fP being
499 In the case of an error, the contents of the returned sets and
500 the \fIstruct timeout\fP contents are undefined and should not be used.
502 however never modifies \fIntimeout\fP.
505 all operating systems that support sockets also support
509 many problems in a portable and efficient way that naive programmers try
510 to solve in a more complicated manner using
511 threads, forking, IPCs, signals, memory sharing, and so on.
515 system call has the same functionality as
517 and is somewhat more efficient when monitoring sparse
518 file descriptor sets.
519 It is nowadays widely available, but historically was less portable than
524 API provides an interface that is more efficient than
528 when monitoring large numbers of file descriptors.
530 Here is an example that better demonstrates the true utility of
532 The listing below is a TCP forwarding program that forwards
533 from one TCP port to another.
539 #include <sys/time.h>
540 #include <sys/types.h>
543 #include <sys/socket.h>
544 #include <netinet/in.h>
545 #include <arpa/inet.h>
548 static int forward_port;
551 #define max(x,y) ((x) > (y) ? (x) : (y))
554 listen_socket(int listen_port)
556 struct sockaddr_in addr;
560 lfd = socket(AF_INET, SOCK_STREAM, 0);
567 if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR,
568 &yes, sizeof(yes)) == \-1) {
569 perror("setsockopt");
574 memset(&addr, 0, sizeof(addr));
575 addr.sin_port = htons(listen_port);
576 addr.sin_family = AF_INET;
577 if (bind(lfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
583 printf("accepting connections on port %d\\n", listen_port);
589 connect_socket(int connect_port, char *address)
591 struct sockaddr_in addr;
594 cfd = socket(AF_INET, SOCK_STREAM, 0);
600 memset(&addr, 0, sizeof(addr));
601 addr.sin_port = htons(connect_port);
602 addr.sin_family = AF_INET;
604 if (!inet_aton(address, (struct in_addr *) &addr.sin_addr.s_addr)) {
605 perror("bad IP address format");
610 if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
612 shutdown(cfd, SHUT_RDWR);
619 #define SHUT_FD1 do { \\
621 shutdown(fd1, SHUT_RDWR); \\
627 #define SHUT_FD2 do { \\
629 shutdown(fd2, SHUT_RDWR); \\
635 #define BUF_SIZE 1024
638 main(int argc, char *argv[])
641 int fd1 = \-1, fd2 = \-1;
642 char buf1[BUF_SIZE], buf2[BUF_SIZE];
643 int buf1_avail = 0, buf1_written = 0;
644 int buf2_avail = 0, buf2_written = 0;
647 fprintf(stderr, "Usage\\n\\tfwd <listen\-port> "
648 "<forward\-to\-port> <forward\-to\-ip\-address>\\n");
652 signal(SIGPIPE, SIG_IGN);
654 forward_port = atoi(argv[2]);
656 h = listen_socket(atoi(argv[1]));
663 fd_set readfds, writefds, exceptfds;
671 if (fd1 > 0 && buf1_avail < BUF_SIZE)
672 FD_SET(fd1, &readfds);
673 /* Note: nfds is updated below, when fd1 is added to
675 if (fd2 > 0 && buf2_avail < BUF_SIZE)
676 FD_SET(fd2, &readfds);
678 if (fd1 > 0 && buf2_avail \- buf2_written > 0)
679 FD_SET(fd1, &writefds);
680 if (fd2 > 0 && buf1_avail \- buf1_written > 0)
681 FD_SET(fd2, &writefds);
684 FD_SET(fd1, &exceptfds);
685 nfds = max(nfds, fd1);
688 FD_SET(fd2, &exceptfds);
689 nfds = max(nfds, fd2);
692 ready = select(nfds + 1, &readfds, &writefds, &exceptfds, NULL);
694 if (ready == \-1 && errno == EINTR)
702 if (FD_ISSET(h, &readfds)) {
704 struct sockaddr_in client_addr;
707 addrlen = sizeof(client_addr);
708 memset(&client_addr, 0, addrlen);
709 fd = accept(h, (struct sockaddr *) &client_addr, &addrlen);
715 buf1_avail = buf1_written = 0;
716 buf2_avail = buf2_written = 0;
718 fd2 = connect_socket(forward_port, argv[3]);
722 printf("connect from %s\\n",
723 inet_ntoa(client_addr.sin_addr));
725 /* Skip any events on the old, closed file descriptors. */
730 /* NB: read OOB data before normal reads */
732 if (fd1 > 0 && FD_ISSET(fd1, &exceptfds)) {
735 nbytes = recv(fd1, &c, 1, MSG_OOB);
739 send(fd2, &c, 1, MSG_OOB);
741 if (fd2 > 0 && FD_ISSET(fd2, &exceptfds)) {
744 nbytes = recv(fd2, &c, 1, MSG_OOB);
748 send(fd1, &c, 1, MSG_OOB);
750 if (fd1 > 0 && FD_ISSET(fd1, &readfds)) {
751 nbytes = read(fd1, buf1 + buf1_avail,
752 BUF_SIZE \- buf1_avail);
756 buf1_avail += nbytes;
758 if (fd2 > 0 && FD_ISSET(fd2, &readfds)) {
759 nbytes = read(fd2, buf2 + buf2_avail,
760 BUF_SIZE \- buf2_avail);
764 buf2_avail += nbytes;
766 if (fd1 > 0 && FD_ISSET(fd1, &writefds) && buf2_avail > 0) {
767 nbytes = write(fd1, buf2 + buf2_written,
768 buf2_avail \- buf2_written);
772 buf2_written += nbytes;
774 if (fd2 > 0 && FD_ISSET(fd2, &writefds) && buf1_avail > 0) {
775 nbytes = write(fd2, buf1 + buf1_written,
776 buf1_avail \- buf1_written);
780 buf1_written += nbytes;
783 /* Check if write data has caught read data */
785 if (buf1_written == buf1_avail)
786 buf1_written = buf1_avail = 0;
787 if (buf2_written == buf2_avail)
788 buf2_written = buf2_avail = 0;
790 /* One side has closed the connection, keep
791 writing to the other side until empty */
793 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
795 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
802 The above program properly forwards most kinds of TCP connections
803 including OOB signal data transmitted by \fBtelnet\fP servers.
804 It handles the tricky problem of having data flow in both directions
806 You might think it more efficient to use a
808 call and devote a thread to each stream.
809 This becomes more tricky than you might suspect.
810 Another idea is to set nonblocking I/O using
812 This also has its problems because you end up using
813 inefficient timeouts.
815 The program does not handle more than one simultaneous connection at a
816 time, although it could easily be extended to do this with a linked list
817 of buffers\(emone for each connection.
819 connections cause the current connection to be dropped.
838 .\" This man page was written by Paul Sheer.