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