]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man2/select_tut.2
intro.1, _syscall.2, access.2, arch_prctl.2, cacheflush.2, chown.2, clock_getres...
[thirdparty/man-pages.git] / man2 / select_tut.2
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 2012-08-03 "Linux" "Linux Programmer's Manual"
33 .SH NAME
34 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
35 synchronous I/O multiplexing
36 .SH SYNOPSIS
37 .nf
38 /* According to POSIX.1-2001 */
39 .br
40 .B #include <sys/select.h>
41 .sp
42 /* According to earlier standards */
43 .br
44 .B #include <sys/time.h>
45 .br
46 .B #include <sys/types.h>
47 .br
48 .B #include <unistd.h>
49 .sp
50 .BI "int select(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
51 .BI " fd_set *" exceptfds ", struct timeval *" utimeout );
52 .sp
53 .BI "void FD_CLR(int " fd ", fd_set *" set );
54 .br
55 .BI "int FD_ISSET(int " fd ", fd_set *" set );
56 .br
57 .BI "void FD_SET(int " fd ", fd_set *" set );
58 .br
59 .BI "void FD_ZERO(fd_set *" set );
60 .sp
61 .B #include <sys/select.h>
62 .sp
63 .BI "int pselect(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
64 .BI " fd_set *" exceptfds ", const struct timespec *" ntimeout ,
65 .BI " const sigset_t *" sigmask );
66 .fi
67 .sp
68 .in -4n
69 Feature Test Macro Requirements for glibc (see
70 .BR feature_test_macros (7)):
71 .in
72 .sp
73 .BR pselect ():
74 _POSIX_C_SOURCE\ >=\ 200112L || _XOPEN_SOURCE\ >=\ 600
75 .SH DESCRIPTION
76 .BR select ()
77 (or
78 .BR pselect ())
79 is used to efficiently monitor multiple file descriptors,
80 to see if any of them is, or becomes, "ready";
81 that is, to see whether I/O becomes possible,
82 or an "exceptional condition" has occurred on any of the descriptors.
83
84 Its principal arguments are three "sets" of file descriptors:
85 \fIreadfds\fP, \fIwritefds\fP, and \fIexceptfds\fP.
86 Each set is declared as type
87 .IR fd_set ,
88 and its contents can be manipulated with the macros
89 .BR FD_CLR (),
90 .BR FD_ISSET (),
91 .BR FD_SET (),
92 and
93 .BR FD_ZERO ().
94 A newly declared set should first be cleared using
95 .BR FD_ZERO ().
96 .BR select ()
97 modifies the contents of the sets according to the rules
98 described below; after calling
99 .BR select ()
100 you can test if a file descriptor is still present in a set with the
101 .BR FD_ISSET ()
102 macro.
103 .BR FD_ISSET ()
104 returns nonzero if a specified file descriptor is present in a set
105 and zero if it is not.
106 .BR FD_CLR ()
107 removes a file descriptor from a set.
108 .SS Arguments
109 .TP
110 \fIreadfds\fP
111 This set is watched to see if data is available for reading from any of
112 its file descriptors.
113 After
114 .BR select ()
115 has returned, \fIreadfds\fP will be
116 cleared of all file descriptors except for those that
117 are immediately available for reading.
118 .TP
119 \fIwritefds\fP
120 This set is watched to see if there is space to write data to any of
121 its file descriptors.
122 After
123 .BR select ()
124 has returned, \fIwritefds\fP will be
125 cleared of all file descriptors except for those that
126 are immediately available for writing.
127 .TP
128 \fIexceptfds\fP
129 This set is watched for "exceptional conditions".
130 In practice, only one such exceptional condition is common:
131 the availability of \fIout-of-band\fP (OOB) data for reading
132 from a TCP socket.
133 See
134 .BR recv (2),
135 .BR send (2),
136 and
137 .BR tcp (7)
138 for more details about OOB data.
139 (One other less common case where
140 .BR select (2)
141 indicates an exceptional condition occurs with pseudoterminals
142 in packet mode; see
143 .BR tty_ioctl (4).)
144 After
145 .BR select ()
146 has returned,
147 \fIexceptfds\fP will be cleared of all file descriptors except for those
148 for which an exceptional condition has occurred.
149 .TP
150 \fInfds\fP
151 This is an integer one more than the maximum of any file descriptor in
152 any of the sets.
153 In other words, while adding file descriptors to each of the sets,
154 you must calculate the maximum integer value of all of them,
155 then increment this value by one, and then pass this as \fInfds\fP.
156 .TP
157 \fIutimeout\fP
158 This is the longest time
159 .BR select ()
160 may wait before returning, even if nothing interesting happened.
161 If this value is passed as NULL, then
162 .BR select ()
163 blocks indefinitely waiting for a file descriptor to become ready.
164 \fIutimeout\fP can be set to zero seconds, which causes
165 .BR select ()
166 to return immediately, with information about the readiness
167 of file descriptors at the time of the call.
168 The structure \fIstruct timeval\fP is defined as:
169 .IP
170 .in +4n
171 .nf
172 struct timeval {
173 time_t tv_sec; /* seconds */
174 long tv_usec; /* microseconds */
175 };
176 .fi
177 .in
178 .TP
179 \fIntimeout\fP
180 This argument for
181 .BR pselect ()
182 has the same meaning as
183 .IR utimeout ,
184 but
185 .I "struct timespec"
186 has nanosecond precision as follows:
187 .IP
188 .in +4n
189 .nf
190 struct timespec {
191 long tv_sec; /* seconds */
192 long tv_nsec; /* nanoseconds */
193 };
194 .fi
195 .in
196 .TP
197 \fIsigmask\fP
198 This argument holds a set of signals that the kernel should unblock
199 (i.e., remove from the signal mask of the calling thread),
200 while the caller is blocked inside the
201 .BR pselect ()
202 call (see
203 .BR sigaddset (3)
204 and
205 .BR sigprocmask (2)).
206 It may be NULL,
207 in which case the call does not modify the signal mask on
208 entry and exit to the function.
209 In this case,
210 .BR pselect ()
211 will then behave just like
212 .BR select ().
213 .SS Combining signal and data events
214 .BR pselect ()
215 is useful if you are waiting for a signal as well as
216 for file descriptor(s) to become ready for I/O.
217 Programs that receive signals
218 normally use the signal handler only to raise a global flag.
219 The global flag will indicate that the event must be processed
220 in the main loop of the program.
221 A signal will cause the
222 .BR select ()
223 (or
224 .BR pselect ())
225 call to return with \fIerrno\fP set to \fBEINTR\fP.
226 This behavior is essential so that signals can be processed
227 in the main loop of the program, otherwise
228 .BR select ()
229 would block indefinitely.
230 Now, somewhere
231 in the main loop will be a conditional to check the global flag.
232 So we must ask:
233 what if a signal arrives after the conditional, but before the
234 .BR select ()
235 call?
236 The answer is that
237 .BR select ()
238 would block indefinitely, even though an event is actually pending.
239 This race condition is solved by the
240 .BR pselect ()
241 call.
242 This call can be used to set the signal mask to a set of signals
243 that are only to be received within the
244 .BR pselect ()
245 call.
246 For instance, let us say that the event in question
247 was the exit of a child process.
248 Before the start of the main loop, we
249 would block \fBSIGCHLD\fP using
250 .BR sigprocmask (2).
251 Our
252 .BR pselect ()
253 call would enable
254 .B SIGCHLD
255 by using an empty signal mask.
256 Our program would look like:
257 .PP
258 .nf
259 static volatile sig_atomic_t got_SIGCHLD = 0;
260
261 static void
262 child_sig_handler(int sig)
263 {
264 got_SIGCHLD = 1;
265 }
266
267 int
268 main(int argc, char *argv[])
269 {
270 sigset_t sigmask, empty_mask;
271 struct sigaction sa;
272 fd_set readfds, writefds, exceptfds;
273 int r;
274
275 sigemptyset(&sigmask);
276 sigaddset(&sigmask, SIGCHLD);
277 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
278 perror("sigprocmask");
279 exit(EXIT_FAILURE);
280 }
281
282 sa.sa_flags = 0;
283 sa.sa_handler = child_sig_handler;
284 sigemptyset(&sa.sa_mask);
285 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
286 perror("sigaction");
287 exit(EXIT_FAILURE);
288 }
289
290 sigemptyset(&empty_mask);
291
292 for (;;) { /* main loop */
293 /* Initialize readfds, writefds, and exceptfds
294 before the pselect() call. (Code omitted.) */
295
296 r = pselect(nfds, &readfds, &writefds, &exceptfds,
297 NULL, &empty_mask);
298 if (r == \-1 && errno != EINTR) {
299 /* Handle error */
300 }
301
302 if (got_SIGCHLD) {
303 got_SIGCHLD = 0;
304
305 /* Handle signalled event here; e.g., wait() for all
306 terminated children. (Code omitted.) */
307 }
308
309 /* main body of program */
310 }
311 }
312 .fi
313 .SS Practical
314 So what is the point of
315 .BR select ()?
316 Can't I just read and write to my descriptors whenever I want?
317 The point of
318 .BR select ()
319 is that it watches
320 multiple descriptors at the same time and properly puts the process to
321 sleep if there is no activity.
322 UNIX programmers often find
323 themselves in a position where they have to handle I/O from more than one
324 file descriptor where the data flow may be intermittent.
325 If you were to merely create a sequence of
326 .BR read (2)
327 and
328 .BR write (2)
329 calls, you would
330 find that one of your calls may block waiting for data from/to a file
331 descriptor, while another file descriptor is unused though ready for I/O.
332 .BR select ()
333 efficiently copes with this situation.
334 .SS Select law
335 Many people who try to use
336 .BR select ()
337 come across behavior that is
338 difficult to understand and produces nonportable or borderline results.
339 For instance, the above program is carefully written not to
340 block at any point, even though it does not set its file descriptors to
341 nonblocking mode.
342 It is easy to introduce
343 subtle errors that will remove the advantage of using
344 .BR select (),
345 so here is a list of essentials to watch for when using
346 .BR select ().
347 .TP 4
348 1.
349 You should always try to use
350 .BR select ()
351 without a timeout.
352 Your program
353 should have nothing to do if there is no data available.
354 Code that
355 depends on timeouts is not usually portable and is difficult to debug.
356 .TP
357 2.
358 The value \fInfds\fP must be properly calculated for efficiency as
359 explained above.
360 .TP
361 3.
362 No file descriptor must be added to any set if you do not intend
363 to check its result after the
364 .BR select ()
365 call, and respond appropriately.
366 See next rule.
367 .TP
368 4.
369 After
370 .BR select ()
371 returns, all file descriptors in all sets
372 should be checked to see if they are ready.
373 .TP
374 5.
375 The functions
376 .BR read (2),
377 .BR recv (2),
378 .BR write (2),
379 and
380 .BR send (2)
381 do \fInot\fP necessarily read/write the full amount of data
382 that you have requested.
383 If they do read/write the full amount, it's
384 because you have a low traffic load and a fast stream.
385 This is not always going to be the case.
386 You should cope with the case of your
387 functions managing to send or receive only a single byte.
388 .TP
389 6.
390 Never read/write only in single bytes at a time unless you are really
391 sure that you have a small amount of data to process.
392 It is extremely
393 inefficient not to read/write as much data as you can buffer each time.
394 The buffers in the example below are 1024 bytes although they could
395 easily be made larger.
396 .TP
397 7.
398 The functions
399 .BR read (2),
400 .BR recv (2),
401 .BR write (2),
402 and
403 .BR send (2)
404 as well as the
405 .BR select ()
406 call can return \-1 with
407 .I errno
408 set to \fBEINTR\fP,
409 or with
410 .I errno
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.
418 .TP
419 8.
420 Never call
421 .BR read (2),
422 .BR recv (2),
423 .BR write (2),
424 or
425 .BR send (2)
426 with a buffer length of zero.
427 .TP
428 9.
429 If the functions
430 .BR read (2),
431 .BR recv (2),
432 .BR write (2),
433 and
434 .BR send (2)
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 descriptor to
438 .BR select ()
439 again.
440 In the example below,
441 I close the descriptor immediately, and then set it to \-1
442 to prevent it being included in a set.
443 .TP
444 10.
445 The timeout value must be initialized with each new call to
446 .BR select (),
447 since some operating systems modify the structure.
448 .BR pselect ()
449 however does not modify its timeout structure.
450 .TP
451 11.
452 Since
453 .BR select ()
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.
459 .\" .TP
460 .\" 11.
461 .\" I have heard that the Windows socket layer does not cope with OOB data
462 .\" properly.
463 .\" It also does not cope with
464 .\" .BR select ()
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.)
469 .SS Usleep emulation
470 On systems that do not have a
471 .BR usleep (3)
472 function, you can call
473 .BR select ()
474 with a finite timeout and no file descriptors as
475 follows:
476 .PP
477 .nf
478 struct timeval tv;
479 tv.tv_sec = 0;
480 tv.tv_usec = 200000; /* 0.2 seconds */
481 select(0, NULL, NULL, NULL, &tv);
482 .fi
483 .PP
484 This is guaranteed to work only on UNIX systems, however.
485 .SH RETURN VALUE
486 On success,
487 .BR select ()
488 returns the total number of file descriptors
489 still present in the file descriptor sets.
490
491 If
492 .BR select ()
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).
496
497 A return value of \-1 indicates an error, with \fIerrno\fP being
498 set appropriately.
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.
501 .BR pselect ()
502 however never modifies \fIntimeout\fP.
503 .SH NOTES
504 Generally speaking,
505 all operating systems that support sockets also support
506 .BR select ().
507 .BR select ()
508 can be used to solve
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.
512 .PP
513 The
514 .BR poll (2)
515 system call has the same functionality as
516 .BR select (),
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
520 .BR select ().
521 .PP
522 The Linux-specific
523 .BR epoll (7)
524 API provides an interface that is more efficient than
525 .BR select (2)
526 and
527 .BR poll (2)
528 when monitoring large numbers of file descriptors.
529 .SH EXAMPLE
530 Here is an example that better demonstrates the true utility of
531 .BR select ().
532 The listing below is a TCP forwarding program that forwards
533 from one TCP port to another.
534 .PP
535 .nf
536 #include <stdlib.h>
537 #include <stdio.h>
538 #include <unistd.h>
539 #include <sys/time.h>
540 #include <sys/types.h>
541 #include <string.h>
542 #include <signal.h>
543 #include <sys/socket.h>
544 #include <netinet/in.h>
545 #include <arpa/inet.h>
546 #include <errno.h>
547
548 static int forward_port;
549
550 #undef max
551 #define max(x,y) ((x) > (y) ? (x) : (y))
552
553 static int
554 listen_socket(int listen_port)
555 {
556 struct sockaddr_in a;
557 int s;
558 int yes;
559
560 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
561 perror("socket");
562 return \-1;
563 }
564 yes = 1;
565 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
566 &yes, sizeof(yes)) == \-1) {
567 perror("setsockopt");
568 close(s);
569 return \-1;
570 }
571 memset(&a, 0, sizeof(a));
572 a.sin_port = htons(listen_port);
573 a.sin_family = AF_INET;
574 if (bind(s, (struct sockaddr *) &a, sizeof(a)) == \-1) {
575 perror("bind");
576 close(s);
577 return \-1;
578 }
579 printf("accepting connections on port %d\\n", listen_port);
580 listen(s, 10);
581 return s;
582 }
583
584 static int
585 connect_socket(int connect_port, char *address)
586 {
587 struct sockaddr_in a;
588 int s;
589
590 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
591 perror("socket");
592 close(s);
593 return \-1;
594 }
595
596 memset(&a, 0, sizeof(a));
597 a.sin_port = htons(connect_port);
598 a.sin_family = AF_INET;
599
600 if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
601 perror("bad IP address format");
602 close(s);
603 return \-1;
604 }
605
606 if (connect(s, (struct sockaddr *) &a, sizeof(a)) == \-1) {
607 perror("connect()");
608 shutdown(s, SHUT_RDWR);
609 close(s);
610 return \-1;
611 }
612 return s;
613 }
614
615 #define SHUT_FD1 do { \\
616 if (fd1 >= 0) { \\
617 shutdown(fd1, SHUT_RDWR); \\
618 close(fd1); \\
619 fd1 = \-1; \\
620 } \\
621 } while (0)
622
623 #define SHUT_FD2 do { \\
624 if (fd2 >= 0) { \\
625 shutdown(fd2, SHUT_RDWR); \\
626 close(fd2); \\
627 fd2 = \-1; \\
628 } \\
629 } while (0)
630
631 #define BUF_SIZE 1024
632
633 int
634 main(int argc, char *argv[])
635 {
636 int h;
637 int fd1 = \-1, fd2 = \-1;
638 char buf1[BUF_SIZE], buf2[BUF_SIZE];
639 int buf1_avail, buf1_written;
640 int buf2_avail, buf2_written;
641
642 if (argc != 4) {
643 fprintf(stderr, "Usage\\n\\tfwd <listen\-port> "
644 "<forward\-to\-port> <forward\-to\-ip\-address>\\n");
645 exit(EXIT_FAILURE);
646 }
647
648 signal(SIGPIPE, SIG_IGN);
649
650 forward_port = atoi(argv[2]);
651
652 h = listen_socket(atoi(argv[1]));
653 if (h == \-1)
654 exit(EXIT_FAILURE);
655
656 for (;;) {
657 int r, nfds = 0;
658 fd_set rd, wr, er;
659
660 FD_ZERO(&rd);
661 FD_ZERO(&wr);
662 FD_ZERO(&er);
663 FD_SET(h, &rd);
664 nfds = max(nfds, h);
665 if (fd1 > 0 && buf1_avail < BUF_SIZE) {
666 FD_SET(fd1, &rd);
667 nfds = max(nfds, fd1);
668 }
669 if (fd2 > 0 && buf2_avail < BUF_SIZE) {
670 FD_SET(fd2, &rd);
671 nfds = max(nfds, fd2);
672 }
673 if (fd1 > 0 && buf2_avail \- buf2_written > 0) {
674 FD_SET(fd1, &wr);
675 nfds = max(nfds, fd1);
676 }
677 if (fd2 > 0 && buf1_avail \- buf1_written > 0) {
678 FD_SET(fd2, &wr);
679 nfds = max(nfds, fd2);
680 }
681 if (fd1 > 0) {
682 FD_SET(fd1, &er);
683 nfds = max(nfds, fd1);
684 }
685 if (fd2 > 0) {
686 FD_SET(fd2, &er);
687 nfds = max(nfds, fd2);
688 }
689
690 r = select(nfds + 1, &rd, &wr, &er, NULL);
691
692 if (r == \-1 && errno == EINTR)
693 continue;
694
695 if (r == \-1) {
696 perror("select()");
697 exit(EXIT_FAILURE);
698 }
699
700 if (FD_ISSET(h, &rd)) {
701 unsigned int l;
702 struct sockaddr_in client_address;
703
704 memset(&client_address, 0, l = sizeof(client_address));
705 r = accept(h, (struct sockaddr *) &client_address, &l);
706 if (r == \-1) {
707 perror("accept()");
708 } else {
709 SHUT_FD1;
710 SHUT_FD2;
711 buf1_avail = buf1_written = 0;
712 buf2_avail = buf2_written = 0;
713 fd1 = r;
714 fd2 = connect_socket(forward_port, argv[3]);
715 if (fd2 == \-1)
716 SHUT_FD1;
717 else
718 printf("connect from %s\\n",
719 inet_ntoa(client_address.sin_addr));
720 }
721 }
722
723 /* NB: read oob data before normal reads */
724
725 if (fd1 > 0)
726 if (FD_ISSET(fd1, &er)) {
727 char c;
728
729 r = recv(fd1, &c, 1, MSG_OOB);
730 if (r < 1)
731 SHUT_FD1;
732 else
733 send(fd2, &c, 1, MSG_OOB);
734 }
735 if (fd2 > 0)
736 if (FD_ISSET(fd2, &er)) {
737 char c;
738
739 r = recv(fd2, &c, 1, MSG_OOB);
740 if (r < 1)
741 SHUT_FD2;
742 else
743 send(fd1, &c, 1, MSG_OOB);
744 }
745 if (fd1 > 0)
746 if (FD_ISSET(fd1, &rd)) {
747 r = read(fd1, buf1 + buf1_avail,
748 BUF_SIZE \- buf1_avail);
749 if (r < 1)
750 SHUT_FD1;
751 else
752 buf1_avail += r;
753 }
754 if (fd2 > 0)
755 if (FD_ISSET(fd2, &rd)) {
756 r = read(fd2, buf2 + buf2_avail,
757 BUF_SIZE \- buf2_avail);
758 if (r < 1)
759 SHUT_FD2;
760 else
761 buf2_avail += r;
762 }
763 if (fd1 > 0)
764 if (FD_ISSET(fd1, &wr)) {
765 r = write(fd1, buf2 + buf2_written,
766 buf2_avail \- buf2_written);
767 if (r < 1)
768 SHUT_FD1;
769 else
770 buf2_written += r;
771 }
772 if (fd2 > 0)
773 if (FD_ISSET(fd2, &wr)) {
774 r = write(fd2, buf1 + buf1_written,
775 buf1_avail \- buf1_written);
776 if (r < 1)
777 SHUT_FD2;
778 else
779 buf1_written += r;
780 }
781
782 /* check if write data has caught read data */
783
784 if (buf1_written == buf1_avail)
785 buf1_written = buf1_avail = 0;
786 if (buf2_written == buf2_avail)
787 buf2_written = buf2_avail = 0;
788
789 /* one side has closed the connection, keep
790 writing to the other side until empty */
791
792 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
793 SHUT_FD2;
794 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
795 SHUT_FD1;
796 }
797 exit(EXIT_SUCCESS);
798 }
799 .fi
800 .PP
801 The above program properly forwards most kinds of TCP connections
802 including OOB signal data transmitted by \fBtelnet\fP servers.
803 It handles the tricky problem of having data flow in both directions
804 simultaneously.
805 You might think it more efficient to use a
806 .BR fork (2)
807 call and devote a thread to each stream.
808 This becomes more tricky than you might suspect.
809 Another idea is to set nonblocking I/O using
810 .BR fcntl (2).
811 This also has its problems because you end up using
812 inefficient timeouts.
813
814 The program does not handle more than one simultaneous connection at a
815 time, although it could easily be extended to do this with a linked list
816 of buffers\(emone for each connection.
817 At the moment, new
818 connections cause the current connection to be dropped.
819 .SH SEE ALSO
820 .BR accept (2),
821 .BR connect (2),
822 .BR ioctl (2),
823 .BR poll (2),
824 .BR read (2),
825 .BR recv (2),
826 .BR select (2),
827 .BR send (2),
828 .BR sigprocmask (2),
829 .BR write (2),
830 .BR sigaddset (3),
831 .BR sigdelset (3),
832 .BR sigemptyset (3),
833 .BR sigfillset (3),
834 .BR sigismember (3),
835 .BR epoll (7)
836 .\" .SH AUTHORS
837 .\" This man page was written by Paul Sheer.