Debian Codegraph @

upstream/debian-unstable/man2/select_tut.2

raw
1 .\" Copyright 2001, Paul Sheer
2 .\" Copyright, the authors of the Linux man-pages project
3 .\"
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .\"
6 .TH SELECT_TUT 2 2026-02-08 "Linux man-pages 6.18"
7 .SH NAME
8 select, pselect \- synchronous I/O multiplexing
9 .SH LIBRARY
10 Standard C library
11 .RI ( libc ,\~ \-lc )
12 .SH SYNOPSIS
13 See
14 .BR select (2)
15 .SH DESCRIPTION
16 The
17 .BR select ()
18 and
19 .BR pselect ()
20 system calls are used to efficiently monitor multiple file descriptors,
21 to see if any of them is, or becomes, "ready";
22 that is, to see whether I/O becomes possible,
23 or an "exceptional condition" has occurred on any of the file descriptors.
24 .P
25 This page provides background and tutorial information
26 on the use of these system calls.
27 For details of the arguments and semantics of
28 .BR select ()
29 and
30 .BR pselect (),
31 see
32 .BR select (2).
33 .\"
34 .SS Combining signal and data events
35 .BR pselect ()
36 is useful if you are waiting for a signal as well as
37 for file descriptor(s) to become ready for I/O.
38 Programs that receive signals
39 normally use the signal handler only to raise a global flag.
40 The global flag will indicate that the event must be processed
41 in the main loop of the program.
42 A signal will cause the
43 .BR select ()
44 (or
45 .BR pselect ())
46 call to return with
47 .I errno
48 set to
49 .BR EINTR .
50 This behavior is essential so that signals can be processed
51 in the main loop of the program, otherwise
52 .BR select ()
53 would block indefinitely.
54 .P
55 Now, somewhere
56 in the main loop will be a conditional to check the global flag.
57 So we must ask:
58 what if a signal arrives after the conditional, but before the
59 .BR select ()
60 call?
61 The answer is that
62 .BR select ()
63 would block indefinitely, even though an event is actually pending.
64 This race condition is solved by the
65 .BR pselect ()
66 call.
67 This call can be used to set the signal mask to a set of signals
68 that are to be received only within the
69 .BR pselect ()
70 call.
71 For instance, let us say that the event in question
72 was the exit of a child process.
73 Before the start of the main loop, we
74 would block
75 .B SIGCHLD
76 using
77 .BR sigprocmask (2).
78 Our
79 .BR pselect ()
80 call would enable
81 .B SIGCHLD
82 by using an empty signal mask.
83 Our program would look like:
84 .P
85 .EX
86 static volatile sig_atomic_t got_SIGCHLD = 0;
87 \&
88 static void
89 child_sig_handler(int sig)
90 {
91 got_SIGCHLD = 1;
92 }
93 \&
94 int
95 main(int argc, char *argv[])
96 {
97 sigset_t sigmask, empty_mask;
98 struct sigaction sa;
99 fd_set readfds, writefds, exceptfds;
100 int r;
101 \&
102 sigemptyset(&sigmask);
103 sigaddset(&sigmask, SIGCHLD);
104 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
105 perror("sigprocmask");
106 exit(EXIT_FAILURE);
107 }
108 \&
109 sa.sa_flags = 0;
110 sa.sa_handler = child_sig_handler;
111 sigemptyset(&sa.sa_mask);
112 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
113 perror("sigaction");
114 exit(EXIT_FAILURE);
115 }
116 \&
117 sigemptyset(&empty_mask);
118 \&
119 for (;;) { /* main loop */
120 /* Initialize readfds, writefds, and exceptfds
121 before the pselect() call. (Code omitted.) */
122 \&
123 r = pselect(nfds, &readfds, &writefds, &exceptfds,
124 NULL, &empty_mask);
125 if (r == \-1 && errno != EINTR) {
126 /* Handle error */
127 }
128 \&
129 if (got_SIGCHLD) {
130 got_SIGCHLD = 0;
131 \&
132 /* Handle signalled event here; e.g., wait() for all
133 terminated children. (Code omitted.) */
134 }
135 \&
136 /* main body of program */
137 }
138 }
139 .EE
140 .SS Practical
141 So what is the point of
142 .BR select ()?
143 Can't I just read and write to my file descriptors whenever I want?
144 The point of
145 .BR select ()
146 is that it watches
147 multiple descriptors at the same time and properly puts the process to
148 sleep if there is no activity.
149 UNIX programmers often find
150 themselves in a position where they have to handle I/O from more than one
151 file descriptor where the data flow may be intermittent.
152 If you were to merely create a sequence of
153 .BR read (2)
154 and
155 .BR write (2)
156 calls, you would
157 find that one of your calls may block waiting for data from/to a file
158 descriptor, while another file descriptor is unused though ready for I/O.
159 .BR select ()
160 efficiently copes with this situation.
161 .SS Select law
162 Many people who try to use
163 .BR select ()
164 come across behavior that is
165 difficult to understand and produces nonportable or borderline results.
166 For instance, the above program is carefully written not to
167 block at any point, even though it does not set its file descriptors to
168 nonblocking mode.
169 It is easy to introduce
170 subtle errors that will remove the advantage of using
171 .BR select (),
172 so here is a list of essentials to watch for when using
173 .BR select ().
174 .TP 4
175 1.
176 You should always try to use
177 .BR select ()
178 without a timeout.
179 Your program
180 should have nothing to do if there is no data available.
181 Code that
182 depends on timeouts is not usually portable and is difficult to debug.
183 .TP
184 2.
185 The value
186 .I nfds
187 must be properly calculated for efficiency
188 as explained above.
189 .TP
190 3.
191 No file descriptor must be added to any set if you do not intend
192 to check its result after the
193 .BR select ()
194 call, and respond appropriately.
195 See next rule.
196 .TP
197 4.
198 After
199 .BR select ()
200 returns, all file descriptors in all sets
201 should be checked to see if they are ready.
202 .TP
203 5.
204 The functions
205 .BR read (2),
206 .BR recv (2),
207 .BR write (2),
208 and
209 .BR send (2)
210 do
211 .I not
212 necessarily read/write the full amount of data
213 that you have requested.
214 If they do read/write the full amount, it's
215 because you have a low traffic load and a fast stream.
216 This is not always going to be the case.
217 You should cope with the case of your
218 functions managing to send or receive only a single byte.
219 .TP
220 6.
221 Never read/write only in single bytes at a time unless you are really
222 sure that you have a small amount of data to process.
223 It is extremely
224 inefficient not to read/write as much data as you can buffer each time.
225 The buffers in the example below are 1024 bytes although they could
226 easily be made larger.
227 .TP
228 7.
229 Calls to
230 .BR read (2),
231 .BR recv (2),
232 .BR write (2),
233 .BR send (2),
234 and
235 .BR select ()
236 can fail with the error
237 .BR EINTR ,
238 and calls to
239 .BR read (2),
240 .BR recv (2),
241 .BR write (2),
242 and
243 .BR send (2)
244 can fail with
245 .I errno
246 set to
247 .B EAGAIN
248 .RB ( EWOULDBLOCK ).
249 These results must be properly managed (not done properly above).
250 If your program is not going to receive any signals, then
251 it is unlikely you will get
252 .BR EINTR .
253 If your program does not set nonblocking I/O,
254 you will not get
255 .BR EAGAIN .
256 .\" Nonetheless, you should still cope with these errors for completeness.
257 .TP
258 8.
259 Never call
260 .BR read (2),
261 .BR recv (2),
262 .BR write (2),
263 or
264 .BR send (2)
265 with a buffer length of zero.
266 .TP
267 9.
268 If the functions
269 .BR read (2),
270 .BR recv (2),
271 .BR write (2),
272 and
273 .BR send (2)
274 fail with errors other than those listed in
275 .BR 7. ,
276 or one of the input functions returns 0, indicating end of file,
277 then you should
278 .I not
279 pass that file descriptor to
280 .BR select ()
281 again.
282 In the example below,
283 I close the file descriptor immediately, and then set it to \-1
284 to prevent it being included in a set.
285 .TP
286 10.
287 The timeout value must be initialized with each new call to
288 .BR select (),
289 since some operating systems modify the structure.
290 .BR pselect ()
291 however does not modify its timeout structure.
292 .TP
293 11.
294 Since
295 .BR select ()
296 modifies its file descriptor sets,
297 if the call is being used in a loop,
298 then the sets must be reinitialized before each call.
299 .\" "I have heard" does not fill me with confidence, and doesn't
300 .\" belong in a man page, so I've commented this point out.
301 .\" .TP
302 .\" 11.
303 .\" I have heard that the Windows socket layer does not cope with OOB data
304 .\" properly.
305 .\" It also does not cope with
306 .\" .BR select ()
307 .\" calls when no file descriptors are set at all.
308 .\" Having no file descriptors set is a useful
309 .\" way to sleep the process with subsecond precision by using the timeout.
310 .\" (See further on.)
311 .SH RETURN VALUE
312 See
313 .BR select (2).
314 .SH NOTES
315 Generally speaking,
316 all operating systems that support sockets also support
317 .BR select ().
318 .BR select ()
319 can be used to solve
320 many problems in a portable and efficient way that naive programmers try
321 to solve in a more complicated manner using
322 threads, forking, IPCs, signals, memory sharing, and so on.
323 .P
324 The
325 .BR poll (2)
326 system call has the same functionality as
327 .BR select (),
328 and is somewhat more efficient when monitoring sparse
329 file descriptor sets.
330 It is nowadays widely available, but historically was less portable than
331 .BR select ().
332 .P
333 The Linux-specific
334 .BR epoll (7)
335 API provides an interface that is more efficient than
336 .BR select (2)
337 and
338 .BR poll (2)
339 when monitoring large numbers of file descriptors.
340 .SH EXAMPLES
341 Here is an example that better demonstrates the true utility of
342 .BR select ().
343 The listing below is a TCP forwarding program that forwards
344 from one TCP port to another.
345 .P
346 .\" SRC BEGIN (select.c)
347 .EX
348 #include <arpa/inet.h>
349 #include <errno.h>
350 #include <netinet/in.h>
351 #include <signal.h>
352 #include <stdio.h>
353 #include <stdlib.h>
354 #include <string.h>
355 #include <sys/select.h>
356 #include <sys/socket.h>
357 #include <sys/types.h>
358 #include <unistd.h>
359 \&
360 static int forward_port;
361 \&
362 #undef max
363 #define max(x, y) ((x) > (y) ? (x) : (y))
364 \&
365 static int
366 listen_socket(int listen_port)
367 {
368 int lfd;
369 int yes;
370 struct sockaddr_in addr;
371 \&
372 lfd = socket(AF_INET, SOCK_STREAM, 0);
373 if (lfd == \-1) {
374 perror("socket");
375 return \-1;
376 }
377 \&
378 yes = 1;
379 if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR,
380 &yes, sizeof(yes)) == \-1)
381 {
382 perror("setsockopt");
383 close(lfd);
384 return \-1;
385 }
386 \&
387 memset(&addr, 0, sizeof(addr));
388 addr.sin_port = htons(listen_port);
389 addr.sin_family = AF_INET;
390 if (bind(lfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
391 perror("bind");
392 close(lfd);
393 return \-1;
394 }
395 \&
396 printf("accepting connections on port %d\[rs]n", listen_port);
397 listen(lfd, 10);
398 return lfd;
399 }
400 \&
401 static int
402 connect_socket(int connect_port, char *address)
403 {
404 int cfd;
405 struct sockaddr_in addr;
406 \&
407 cfd = socket(AF_INET, SOCK_STREAM, 0);
408 if (cfd == \-1) {
409 perror("socket");
410 return \-1;
411 }
412 \&
413 memset(&addr, 0, sizeof(addr));
414 addr.sin_port = htons(connect_port);
415 addr.sin_family = AF_INET;
416 \&
417 if (!inet_aton(address, (struct in_addr *) &addr.sin_addr.s_addr)) {
418 fprintf(stderr, "inet_aton(): bad IP address format\[rs]n");
419 close(cfd);
420 return \-1;
421 }
422 \&
423 if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
424 perror("connect()");
425 shutdown(cfd, SHUT_RDWR);
426 close(cfd);
427 return \-1;
428 }
429 return cfd;
430 }
431 \&
432 #define SHUT_FD1 do { \[rs]
433 if (fd1 >= 0) { \[rs]
434 shutdown(fd1, SHUT_RDWR); \[rs]
435 close(fd1); \[rs]
436 fd1 = \-1; \[rs]
437 } \[rs]
438 } while (0)
439 \&
440 #define SHUT_FD2 do { \[rs]
441 if (fd2 >= 0) { \[rs]
442 shutdown(fd2, SHUT_RDWR); \[rs]
443 close(fd2); \[rs]
444 fd2 = \-1; \[rs]
445 } \[rs]
446 } while (0)
447 \&
448 #define BUF_SIZE 1024
449 \&
450 int
451 main(int argc, char *argv[])
452 {
453 int h;
454 int ready, nfds;
455 int fd1 = \-1, fd2 = \-1;
456 int buf1_avail = 0, buf1_written = 0;
457 int buf2_avail = 0, buf2_written = 0;
458 char buf1[BUF_SIZE], buf2[BUF_SIZE];
459 fd_set readfds, writefds, exceptfds;
460 ssize_t nbytes;
461 \&
462 if (argc != 4) {
463 fprintf(stderr, "Usage\[rs]n\[rs]tfwd <listen\-port> "
464 "<forward\-to\-port> <forward\-to\-ip\-address>\[rs]n");
465 exit(EXIT_FAILURE);
466 }
467 \&
468 signal(SIGPIPE, SIG_IGN);
469 \&
470 forward_port = atoi(argv[2]);
471 \&
472 h = listen_socket(atoi(argv[1]));
473 if (h == \-1)
474 exit(EXIT_FAILURE);
475 \&
476 for (;;) {
477 nfds = 0;
478 \&
479 FD_ZERO(&readfds);
480 FD_ZERO(&writefds);
481 FD_ZERO(&exceptfds);
482 FD_SET(h, &readfds);
483 nfds = max(nfds, h);
484 \&
485 if (fd1 > 0 && buf1_avail < BUF_SIZE)
486 FD_SET(fd1, &readfds);
487 /* Note: nfds is updated below, when fd1 is added to
488 exceptfds. */
489 if (fd2 > 0 && buf2_avail < BUF_SIZE)
490 FD_SET(fd2, &readfds);
491 \&
492 if (fd1 > 0 && buf2_avail \- buf2_written > 0)
493 FD_SET(fd1, &writefds);
494 if (fd2 > 0 && buf1_avail \- buf1_written > 0)
495 FD_SET(fd2, &writefds);
496 \&
497 if (fd1 > 0) {
498 FD_SET(fd1, &exceptfds);
499 nfds = max(nfds, fd1);
500 }
501 if (fd2 > 0) {
502 FD_SET(fd2, &exceptfds);
503 nfds = max(nfds, fd2);
504 }
505 \&
506 ready = select(nfds + 1, &readfds, &writefds, &exceptfds, NULL);
507 \&
508 if (ready == \-1 && errno == EINTR)
509 continue;
510 \&
511 if (ready == \-1) {
512 perror("select()");
513 exit(EXIT_FAILURE);
514 }
515 \&
516 if (FD_ISSET(h, &readfds)) {
517 socklen_t addrlen;
518 struct sockaddr_in client_addr;
519 int fd;
520 \&
521 addrlen = sizeof(client_addr);
522 memset(&client_addr, 0, addrlen);
523 fd = accept(h, (struct sockaddr *) &client_addr, &addrlen);
524 if (fd == \-1) {
525 perror("accept()");
526 } else {
527 SHUT_FD1;
528 SHUT_FD2;
529 buf1_avail = buf1_written = 0;
530 buf2_avail = buf2_written = 0;
531 fd1 = fd;
532 fd2 = connect_socket(forward_port, argv[3]);
533 if (fd2 == \-1)
534 SHUT_FD1;
535 else
536 printf("connect from %s\[rs]n",
537 inet_ntoa(client_addr.sin_addr));
538 \&
539 /* Skip any events on the old, closed file
540 descriptors. */
541 \&
542 continue;
543 }
544 }
545 \&
546 /* NB: read OOB data before normal reads. */
547 \&
548 if (fd1 > 0 && FD_ISSET(fd1, &exceptfds)) {
549 char c;
550 \&
551 nbytes = recv(fd1, &c, 1, MSG_OOB);
552 if (nbytes < 1)
553 SHUT_FD1;
554 else
555 send(fd2, &c, 1, MSG_OOB);
556 }
557 if (fd2 > 0 && FD_ISSET(fd2, &exceptfds)) {
558 char c;
559 \&
560 nbytes = recv(fd2, &c, 1, MSG_OOB);
561 if (nbytes < 1)
562 SHUT_FD2;
563 else
564 send(fd1, &c, 1, MSG_OOB);
565 }
566 if (fd1 > 0 && FD_ISSET(fd1, &readfds)) {
567 nbytes = read(fd1, buf1 + buf1_avail,
568 BUF_SIZE \- buf1_avail);
569 if (nbytes < 1)
570 SHUT_FD1;
571 else
572 buf1_avail += nbytes;
573 }
574 if (fd2 > 0 && FD_ISSET(fd2, &readfds)) {
575 nbytes = read(fd2, buf2 + buf2_avail,
576 BUF_SIZE \- buf2_avail);
577 if (nbytes < 1)
578 SHUT_FD2;
579 else
580 buf2_avail += nbytes;
581 }
582 if (fd1 > 0 && FD_ISSET(fd1, &writefds) && buf2_avail > 0) {
583 nbytes = write(fd1, buf2 + buf2_written,
584 buf2_avail \- buf2_written);
585 if (nbytes < 1)
586 SHUT_FD1;
587 else
588 buf2_written += nbytes;
589 }
590 if (fd2 > 0 && FD_ISSET(fd2, &writefds) && buf1_avail > 0) {
591 nbytes = write(fd2, buf1 + buf1_written,
592 buf1_avail \- buf1_written);
593 if (nbytes < 1)
594 SHUT_FD2;
595 else
596 buf1_written += nbytes;
597 }
598 \&
599 /* Check if write data has caught read data. */
600 \&
601 if (buf1_written == buf1_avail)
602 buf1_written = buf1_avail = 0;
603 if (buf2_written == buf2_avail)
604 buf2_written = buf2_avail = 0;
605 \&
606 /* One side has closed the connection, keep
607 writing to the other side until empty. */
608 \&
609 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
610 SHUT_FD2;
611 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
612 SHUT_FD1;
613 }
614 exit(EXIT_SUCCESS);
615 }
616 .EE
617 .\" SRC END
618 .P
619 The above program properly forwards most kinds of TCP connections
620 including OOB signal data transmitted by
621 .B telnet
622 servers.
623 It handles the tricky problem of having data flow in both directions
624 simultaneously.
625 You might think it more efficient to use a
626 .BR fork (2)
627 call and devote a thread to each stream.
628 This becomes more tricky than you might suspect.
629 Another idea is to set nonblocking I/O using
630 .BR fcntl (2).
631 This also has its problems because you end up using
632 inefficient timeouts.
633 .P
634 The program does not handle more than one simultaneous connection at a
635 time, although it could easily be extended to do this with a linked list
636 of buffers\[em]one for each connection.
637 At the moment, new
638 connections cause the current connection to be dropped.
639 .SH SEE ALSO
640 .BR accept (2),
641 .BR connect (2),
642 .BR poll (2),
643 .BR read (2),
644 .BR recv (2),
645 .BR select (2),
646 .BR send (2),
647 .BR sigprocmask (2),
648 .BR write (2),
649 .BR epoll (7)
650 .\" .SH AUTHORS
651 .\" This man page was written by Paul Sheer.