Debian Codegraph @

upstream/debian-trixie/man2/select_tut.2

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