1 .\" This manpage is copyright (C) 2001 Paul Sheer.
3 .\" Permission is granted to make and distribute verbatim copies of this
4 .\" manual provided the copyright notice and this permission notice are
5 .\" preserved on all copies.
7 .\" Permission is granted to copy and distribute modified versions of this
8 .\" manual under the conditions for verbatim copying, provided that the
9 .\" entire resulting derived work is distributed under the terms of a
10 .\" permission notice identical to this one.
12 .\" Since the Linux kernel and libraries are constantly changing, this
13 .\" manual page may be incorrect or out-of-date. The author(s) assume no
14 .\" responsibility for errors or omissions, or for damages resulting from
15 .\" the use of the information contained herein. The author(s) may not
16 .\" have taken the same level of care in the production of this manual,
17 .\" which is licensed free of charge, as they might when working
20 .\" Formatted or processed versions of this manual, if unaccompanied by
21 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" very minor changes, aeb
25 .\" Modified 5 June 2002, Michael Kerrisk <mtk.manpages@gmail.com>
26 .\" 2006-05-13, mtk, removed much material that is redundant with select.2
27 .\" various other changes
28 .\" 2008-01-26, mtk, substantial changes and rewrites
30 .\" Translated 2002-02-21, NAKANO Takeo <nakano@apm.seikei.ac.jp>
31 .\" Updated 2002-09-23, Akihiro MOTOKI <amotoki@dd.iij4u.or.jp>
32 .\" Updated 2005-03-15, Akihiro MOTOKI <amotoki@dd.iij4u.or.jp>
33 .\" Updated 2006-07-21, Akihiro MOTOKI, LDP v2.36
34 .\" Updated 2009-02-13, Akihiro MOTOKI, LDP v3.18
36 .\"WORD: file descriptor ファイルディスクリプタ
37 .\"WORD: exceptional condition 例外状態
39 .TH SELECT_TUT 2 2010-06-10 "Linux" "Linux Programmer's Manual"
42 .\"O select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \-
43 .\"O synchronous I/O multiplexing
44 select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO \- 同期 I/O の多重化
48 .\"O /* According to POSIX.1-2001 */
49 /* POSIX.1-2001 に従う場合 */
51 .B #include <sys/select.h>
53 .\"O /* According to earlier standards */
56 .B #include <sys/time.h>
58 .B #include <sys/types.h>
60 .B #include <unistd.h>
62 .BI "int select(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
63 .BI " fd_set *" exceptfds ", struct timeval *" utimeout );
65 .BI "void FD_CLR(int " fd ", fd_set *" set );
67 .BI "int FD_ISSET(int " fd ", fd_set *" set );
69 .BI "void FD_SET(int " fd ", fd_set *" set );
71 .BI "void FD_ZERO(fd_set *" set );
73 .B #include <sys/select.h>
75 .BI "int pselect(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
76 .BI " fd_set *" exceptfds ", const struct timespec *" ntimeout ,
77 .BI " const sigset_t *" sigmask );
81 .\"O Feature Test Macro Requirements for glibc (see
82 .\"O .BR feature_test_macros (7)):
84 .RB ( feature_test_macros (7)
89 _POSIX_C_SOURCE\ >=\ 200112L || _XOPEN_SOURCE\ >=\ 600
95 .\"O is used to efficiently monitor multiple file descriptors,
96 .\"O to see if any of them is, or becomes, "ready";
97 .\"O that is, to see whether I/O becomes possible,
98 .\"O or an "exceptional condition" has occurred on any of the descriptors.
102 を使うと、効率的に複数のファイルディスクリプタを監視し、
104 「ready (準備ができた)」状態、つまり I/O (入出力) が可能になっているかや、
106 「例外状態 (exceptional condition)」が発生したか、を調べることができる。
108 .\"O Its principal arguments are three "sets" of file descriptors:
109 .\"O \fIreadfds\fP, \fIwritefds\fP, and \fIexceptfds\fP.
110 この関数の主要な引き数は、3種類のファイルディスクリプタの「集合」
111 \fIreadfds\fP, \fIwritefds\fP, \fIexceptfds\fP である。
112 .\"O Each set is declared as type
114 .\"O and its contents can be manipulated with the macros
116 .\"O .BR FD_ISSET (),
120 .\"O A newly declared set should first be cleared using
134 .\"O modifies the contents of the sets according to the rules
135 .\"O described below; after calling
137 .\"O you can test if a file descriptor is still present in a set with the
141 .\"O returns nonzero if a specified file descriptor is present in a set
142 .\"O and zero if it is not.
144 .\"O removes a file descriptor from a set.
146 はこれらの集合の内容を、以降に述べる規則に従って修正する。
148 を呼んだ後、ファイルディスクリプタがまだ集合に存在しているかどうかは、
152 は指定されたディスクリプタが集合に存在していれば 0 以外の値を返し、
155 は集合からのファイルディスクリプタの削除を行う。
160 .\"O This set is watched to see if data is available for reading from any of
161 .\"O its file descriptors.
164 .\"O has returned, \fIreadfds\fP will be
165 .\"O cleared of all file descriptors except for those that
166 .\"O are immediately available for reading.
167 この集合に含まれるいずれかのファイルディスクリプタで、
168 データの読み込みが可能になったかどうかを監視する。
170 から戻る時に、\fIreadfds\fP のうち、
171 直ちに読み込み可能なファイルディスクリプタ以外は
175 .\"O This set is watched to see if there is space to write data to any of
176 .\"O its file descriptors.
179 .\"O has returned, \fIwritefds\fP will be
180 .\"O cleared of all file descriptors except for those that
181 .\"O are immediately available for writing.
182 この集合に含まれるいずれかのファイルディスクリプタで、
183 データを書き込むスペースがあるかどうかを監視する。
185 から戻る時に、\fIwritefds\fP のうち、
186 直ちに書き込み可能なファイルディスクリプタ以外は
190 .\"O This set is watched for "exceptional conditions".
191 .\"O In practice, only one such exceptional condition is common:
192 .\"O the availability of \fIout-of-band\fP (OOB) data for reading
193 .\"O from a TCP socket.
199 .\"O for more details about OOB data.
200 .\"O (One other less common case where
202 .\"O indicates an exceptional condition occurs with pseudoterminals
203 .\"O in packet mode; see
204 .\"O .BR tty_ioctl (4).)
208 .\"O \fIexceptfds\fP will be cleared of all file descriptors except for those
209 .\"O for which an exceptional condition has occurred.
210 この集合に含まれるいずれかのファイルディスクリプタで、
211 「例外状態 (exceptional condition)」が発生したかどうかを監視する。
212 実際の動作では、普通に起こり得る例外状態は一つだけであり、
213 それは TCP ソケットで \fI帯域外 (out-of-band; OOB)\fP データが
221 パケットモードの擬似端末 (pseudoterminals) で
225 が返る時に、\fIexceptfds\fP のうち、
226 例外状態が発生したディスクリプタ以外は集合から削除される。
229 .\"O This is an integer one more than the maximum of any file descriptor in
230 .\"O any of the sets.
231 .\"O In other words, while adding file descriptors to each of the sets,
232 .\"O you must calculate the maximum integer value of all of them,
233 .\"O then increment this value by one, and then pass this as \fInfds\fP.
234 全ての集合に含まれるファイルディスクリプタのうち、
235 値が最大のものに 1 を足した整数である。
236 すなわち、ファイルディスクリプタを各集合に加える作業の途中で、
237 全てのファイルディスクリプタを見て最大値を求め、
238 それに 1 を加えて \fInfds\fP として渡さないといけない、ということだ。
241 .\"O This is the longest time
243 .\"O may wait before returning, even if nothing interesting happened.
244 .\"O If this value is passed as NULL, then
246 .\"O blocks indefinitely waiting for a file descriptor to become ready.
247 .\"O \fIutimeout\fP can be set to zero seconds, which causes
249 .\"O to return immediately, with information about the readiness
250 .\"O of file descriptors at the time of the call.
251 .\"O The structure \fIstruct timeval\fP is defined as:
257 はファイルディスクリプタのいずれかが ready (準備ができた) 状態に
259 \fIutimeout\fP は 0 秒にすることもでき、
262 は直ちに返り、呼び出し時点のファイルディスクリプタの状態に
264 構造体 \fIstruct timeval\fP は次のように定義されている:
269 time_t tv_sec; /* seconds */
270 long tv_usec; /* microseconds */
276 .\"O This argument for
278 .\"O has the same meaning as
281 .\"O .I "struct timespec"
282 .\"O has nanosecond precision as follows:
292 long tv_sec; /* seconds */
293 long tv_nsec; /* nanoseconds */
299 .\"O This argument holds a set of signals that the kernel should unblock
300 .\"O (i.e., remove from the signal mask of the calling thread),
301 .\"O while the caller is blocked inside the
304 .\"O .BR sigaddset (3)
306 .\"O .BR sigprocmask (2)).
308 .\"O in which case the call does not modify the signal mask on
309 .\"O entry and exit to the function.
312 .\"O will then behave just like
316 内部で停止している間に、カーネルが通知を許可すべきシグナル集合
317 (すなわち、呼び出したスレッドのシグナルマスクから削除すべきシグナル集合)
323 この引き数は NULL にすることもでき、その場合はこの関数へ
324 入るとき・出るときにシグナルマスクを変更しない。
330 .\"O .SS Combining Signal and Data Events
331 .SS シグナルとデータイベントを組み合わせる
333 .\"O is useful if you are waiting for a signal as well as
334 .\"O for file descriptor(s) to become ready for I/O.
335 .\"O Programs that receive signals
336 .\"O normally use the signal handler only to raise a global flag.
337 .\"O The global flag will indicate that the event must be processed
338 .\"O in the main loop of the program.
339 ファイルディスクリプタが I/O 可能な状態になるのと同時に
344 シグナルハンドラをグローバルなフラグを立てるためだけに使う。
348 .\"O A signal will cause the
352 .\"O call to return with \fIerrno\fP set to \fBEINTR\fP.
353 .\"O This behavior is essential so that signals can be processed
354 .\"O in the main loop of the program, otherwise
356 .\"O would block indefinitely.
362 \fIerrno\fP に \fBEINTR\fP をセットして戻ることになる。
363 シグナルがプログラムのメインループで処理されるためにはこの動作が不可欠で、
368 .\"O in the main loop will be a conditional to check the global flag.
370 .\"O what if a signal arrives after the conditional, but before the
373 .\"O The answer is that
375 .\"O would block indefinitely, even though an event is actually pending.
376 さて、メインループのどこかにこのグローバルフラグをチェックする
377 条件文があるとしよう。ここで少し考えてみないといけない。
384 は、たとえ解決待ちのイベントがあったとしても、
386 .\"O This race condition is solved by the
389 .\"O This call can be used to set the signal mask to a set of signals
390 .\"O that are only to be received within the
398 で受信したいシグナルの集合だけをシグナルマスクに設定することができる。
399 .\"O For instance, let us say that the event in question
400 .\"O was the exit of a child process.
401 .\"O Before the start of the main loop, we
402 .\"O would block \fBSIGCHLD\fP using
403 .\"O .BR sigprocmask (2).
406 .\"O call would enable
408 .\"O by using an empty signal mask.
409 .\"O Our program would look like:
410 例えば、問題となっているイベントが子プロセスの終了の場合を考えよう。
419 を、もともとのシグナルマスクを使って有効にするのだ。
423 static volatile sig_atomic_t got_SIGCHLD = 0;
426 child_sig_handler(int sig)
432 main(int argc, char *argv[])
434 sigset_t sigmask, empty_mask;
436 fd_set readfds, writefds, exceptfds;
439 sigemptyset(&sigmask);
440 sigaddset(&sigmask, SIGCHLD);
441 if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
442 perror("sigprocmask");
447 sa.sa_handler = child_sig_handler;
448 sigemptyset(&sa.sa_mask);
449 if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
454 sigemptyset(&empty_mask);
456 for (;;) { /* main loop */
457 /* Initialize readfds, writefds, and exceptfds
458 before the pselect() call. (Code omitted.) */
460 r = pselect(nfds, &readfds, &writefds, &exceptfds,
462 if (r == \-1 && errno != EINTR) {
469 /* Handle signalled event here; e.g., wait() for all
470 terminated children. (Code omitted.) */
473 /* main body of program */
479 .\"O So what is the point of
481 .\"O Can't I just read and write to my descriptors whenever I want?
484 .\"O is that it watches
485 .\"O multiple descriptors at the same time and properly puts the process to
486 .\"O sleep if there is no activity.
487 .\"O UNIX programmers often find
488 .\"O themselves in a position where they have to handle I/O from more than one
489 .\"O file descriptor where the data flow may be intermittent.
490 .\"O If you were to merely create a sequence of
494 .\"O calls, you would
495 .\"O find that one of your calls may block waiting for data from/to a file
496 .\"O descriptor, while another file descriptor is unused though ready for I/O.
498 .\"O efficiently copes with this situation.
502 ディスクリプタは好きなときに読み書きできるんじゃないの?
504 の重要なところは、複数のディスクリプタを同時に監視でき、
505 なんの動きもなければプロセスを適切にスリープ状態に移行するところにあるのだ。
507 複数のファイルディスクリプタの入出力を同時に扱わねばならず、
508 しかもデータの流れは間欠的である、という状況によく出会う。
513 コールのシーケンスを作るだけでは、それらのコールのどれかが
514 ファイルディスクリプタからのデータを待ってブロックしており、
515 別のファイルディスクリプタには I/O が可能なのに使えない、
521 .\"O Many people who try to use
523 .\"O come across behavior that is
524 .\"O difficult to understand and produces nonportable or borderline results.
525 .\"O For instance, the above program is carefully written not to
526 .\"O block at any point, even though it does not set its file descriptors to
527 .\"O nonblocking mode.
528 .\"O It is easy to introduce
529 .\"O subtle errors that will remove the advantage of using
531 .\"O so here is a list of essentials to watch for when using
534 を使おうとした多くの人は、理解しにくい挙動に出くわし、結果的に
535 できたものは移植性がないか、よくてもギリギリのものになってしまう。
537 集合に含まれるファイルディスクリプタを非停止 (nonblocking) モード
538 にしなくても、どこにもブロックが生じないよう注意して書かれている。
544 コールを使うときに注意すべき重要事項を列挙しておくことにする。
547 .\"O You should always try to use
549 .\"O without a timeout.
551 .\"O should have nothing to do if there is no data available.
553 .\"O depends on timeouts is not usually portable and is difficult to debug.
555 を使うときは、タイムアウトは設定すべきでない。
557 あなたのプログラムには何もすることは無いはずである。
558 タイムアウトに依存したコードは通常移植性がなく、
562 .\"O The value \fInfds\fP must be properly calculated for efficiency as
563 .\"O explained above.
567 の値を適切に計算して与えなければならない。
570 .\"O No file descriptor must be added to any set if you do not intend
571 .\"O to check its result after the
573 .\"O call, and respond appropriately.
577 適切に対応するつもりのないファイルディスクリプタは、
584 .\"O returns, all file descriptors in all sets
585 .\"O should be checked to see if they are ready.
587 から返った後には、全ての集合の全てのファイルディスクリプタについて
588 読み書き可能な状態になっているかをチェックすべきである。
597 .\"O do \fInot\fP necessarily read/write the full amount of data
598 .\"O that you have requested.
599 .\"O If they do read/write the full amount, it's
600 .\"O because you have a low traffic load and a fast stream.
601 .\"O This is not always going to be the case.
602 .\"O You should cope with the case of your
603 .\"O functions only managing to send or receive a single byte.
608 といった関数は、こちらが要求した全データを読み書きする必要は\fIない\fP。
609 もし全データを読み書きするなら、それはトラフィックの負荷が小さく、
610 ストリームが速い場合だろう。この条件は常に満たされるとは限らない。
611 これらの関数が頑張っても 1 バイトしか送受信できないような場合も
615 .\"O Never read/write only in single bytes at a time unless you are really
616 .\"O sure that you have a small amount of data to process.
618 .\"O inefficient not to read/write as much data as you can buffer each time.
619 .\"O The buffers in the example below are 1024 bytes although they could
620 .\"O easily be made larger.
621 処理するデータ量が小さいことがはっきりとわかっている場合を除いて、
622 一度に 1 バイトずつ読み書きするようなことはしてはならない。
623 バッファの許すかぎりのデータをまとめて読み書きしないと、
624 非常に効率が悪い。下記の例ではバッファは 1024 バイトにしているが、
636 .\"O call can return \-1 with
638 .\"O set to \fBEINTR\fP,
641 .\"O set to \fBEAGAIN\fP (\fBEWOULDBLOCK\fP).
642 .\"O These results must be properly managed (not done properly above).
643 .\"O If your program is not going to receive any signals, then
644 .\"O it is unlikely you will get \fBEINTR\fP.
645 .\"O If your program does not set nonblocking I/O,
646 .\"O you will not get \fBEAGAIN\fP.
647 .\"O .\" Nonetheless, you should still cope with these errors for completeness.
657 .B EINTR " や " EAGAIN
660 このような結果に対して適切に対応してやらなければならない
662 書いているプログラムがシグナルを受ける予定がなければ、
665 書いているプログラムで非ブロック I/O をセットしていない場合は、
668 .\" それでもなお、完全を期するならば、
669 .\" これらのエラーを考慮に入れる必要がある。
678 .\"O with a buffer length of zero.
679 決して、引き数に長さ 0 のバッファを指定して
687 .\"O If the functions
693 .\"O fail with errors other than those listed in \fB7.\fP,
694 .\"O or one of the input functions returns 0, indicating end of file,
695 .\"O then you should \fInot\fP pass that descriptor to
698 .\"O In the example below,
699 .\"O I close the descriptor immediately, and then set it to \-1
700 .\"O to prevent it being included in a set.
706 \fB7.\fP に示した以外のエラーで失敗した場合や、
707 入力系の関数の一つがファイル末尾を表す 0 を返した場合は、
708 そのディスクリプタをもう一度 select に渡しては\fIならない\fP。
709 下記の例では、そのディスクリプタをただちにクローズし、
711 それが集合に含まれ続けるのを許さないようにしている。
714 .\"O The timeout value must be initialized with each new call to
716 .\"O since some operating systems modify the structure.
718 .\"O however does not modify its timeout structure.
722 OS によっては timeout 構造体が変更される場合があるからである。
725 は自分の timeout 構造体を変更することはない。
730 .\"O modifies its file descriptor sets,
731 .\"O if the call is being used in a loop,
732 .\"O then the sets must be reinitialized before each call.
734 はファイルディスクリプタ集合を変更するので、
736 がループの中で使用されている場合には、呼び出しを行う前に毎回
737 ディスクリプタ集合を初期化し直さなければならない。
738 .\" "I have heard" does not fill me with confidence, and doesn't
739 .\" belong in a man page, so I've commented this point out.
742 .\"O .\" I have heard that the Windows socket layer does not cope with OOB data
744 .\"O .\" It also does not cope with
745 .\"O .\" .BR select ()
746 .\"O .\" calls when no file descriptors are set at all.
747 .\"O .\" Having no file descriptors set is a useful
748 .\"O .\" way to sleep the process with subsecond precision by using the timeout.
749 .\"O .\" (See further on.)
750 .\" 聞いたところでは、Windows のソケット層は
751 .\" OOB データを正しく処理しないらしい。
752 .\" また、ファイルディスクリプタが全くセットされていないような
755 .\" ファイルディスクリプタを一切設定しないで timeout を使うやり方は、
756 .\" 1 秒以下の精度でプロセスをスリープさせるには便利な方法なのだが
758 .\"O .SS Usleep Emulation
760 .\"O On systems that do not have a
762 .\"O function, you can call
764 .\"O with a finite timeout and no file descriptors as
768 有限のタイムアウトを指定し、ファイルディスクリプタを全くセットせずに
776 tv.tv_usec = 200000; /* 0.2 seconds */
777 select(0, NULL, NULL, NULL, &tv);
780 .\"O This is only guaranteed to work on UNIX systems, however.
781 但し、これが動くと保証されているのは UNIX システムに限られる。
782 .\"O .SH RETURN VALUE
786 .\"O returns the total number of file descriptors
787 .\"O still present in the file descriptor sets.
795 .\"O timed out, then the return value will be zero.
796 .\"O The file descriptors set should be all
797 .\"O empty (but may not be on some systems).
799 がタイムアウトすると、返り値は 0 になる。
800 その時、ファイルディスクリプタ集合はすべて空である
803 .\"O A return value of \-1 indicates an error, with \fIerrno\fP being
804 .\"O set appropriately.
805 .\"O In the case of an error, the contents of the returned sets and
806 .\"O the \fIstruct timeout\fP contents are undefined and should not be used.
808 .\"O however never modifies \fIntimeout\fP.
809 返り値が \-1 の場合はエラーを意味し、
811 が適切にセットされる。エラーが起こった場合、
812 返された集合の内容や構造体 \fIstruct timeout\fP の内容は
821 .\"O Generally speaking,
822 .\"O all operating systems that support sockets also support
825 .\"O can be used to solve
826 .\"O many problems in a portable and efficient way that naive programmers try
827 .\"O to solve in a more complicated manner using
828 .\"O threads, forking, IPCs, signals, memory sharing, and so on.
829 一般的に言って、ソケットをサポートする全てのオペレーティングシステムは
833 を使うと、プログラマがスレッド、フォーク、IPC、シグナル、メモリ共有、
834 等々を使ってもっと複雑な方法で解決しようとする多くの問題が、
835 移植性がありかつ効率的な方法で解決できる。
839 .\"O system call has the same functionality as
841 .\"O and is somewhat more efficient when monitoring sparse
842 .\"O file descriptor sets.
843 .\"O It is nowadays widely available, but historically was less portable than
849 まばらなファイルディスクリプタ集合を監視する場合に
855 .\"O The Linux-specific
857 .\"O API provides an interface that is more efficient than
861 .\"O when monitoring large numbers of file descriptors.
864 API は、多数のファイルディスクリプタを監視する場合に
868 よりも効率的なインタフェースを提供している。
871 .\"O Here is an example that better demonstrates the true utility of
873 .\"O The listing below a TCP forwarding program that forwards
874 .\"O from one TCP port to another.
876 の本当に便利な点を示す、よい例を紹介する。
877 以下のリストは、ある TCP ポートから別のポートへ転送を行う
884 #include <sys/time.h>
885 #include <sys/types.h>
888 #include <sys/socket.h>
889 #include <netinet/in.h>
890 #include <arpa/inet.h>
893 static int forward_port;
896 #define max(x,y) ((x) > (y) ? (x) : (y))
899 listen_socket(int listen_port)
901 struct sockaddr_in a;
905 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
910 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
911 (char *) &yes, sizeof(yes)) == \-1) {
912 perror("setsockopt");
916 memset(&a, 0, sizeof(a));
917 a.sin_port = htons(listen_port);
918 a.sin_family = AF_INET;
919 if (bind(s, (struct sockaddr *) &a, sizeof(a)) == \-1) {
924 printf("accepting connections on port %d\\n", listen_port);
930 connect_socket(int connect_port, char *address)
932 struct sockaddr_in a;
935 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
941 memset(&a, 0, sizeof(a));
942 a.sin_port = htons(connect_port);
943 a.sin_family = AF_INET;
945 if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
946 perror("bad IP address format");
951 if (connect(s, (struct sockaddr *) &a, sizeof(a)) == \-1) {
953 shutdown(s, SHUT_RDWR);
960 #define SHUT_FD1 do { \\
962 shutdown(fd1, SHUT_RDWR); \\
968 #define SHUT_FD2 do { \\
970 shutdown(fd2, SHUT_RDWR); \\
976 #define BUF_SIZE 1024
979 main(int argc, char *argv[])
982 int fd1 = \-1, fd2 = \-1;
983 char buf1[BUF_SIZE], buf2[BUF_SIZE];
984 int buf1_avail, buf1_written;
985 int buf2_avail, buf2_written;
988 fprintf(stderr, "Usage\\n\\tfwd <listen-port> "
989 "<forward-to-port> <forward-to-ip-address>\\n");
993 signal(SIGPIPE, SIG_IGN);
995 forward_port = atoi(argv[2]);
997 h = listen_socket(atoi(argv[1]));
1009 nfds = max(nfds, h);
1010 if (fd1 > 0 && buf1_avail < BUF_SIZE) {
1012 nfds = max(nfds, fd1);
1014 if (fd2 > 0 && buf2_avail < BUF_SIZE) {
1016 nfds = max(nfds, fd2);
1018 if (fd1 > 0 && buf2_avail \- buf2_written > 0) {
1020 nfds = max(nfds, fd1);
1022 if (fd2 > 0 && buf1_avail \- buf1_written > 0) {
1024 nfds = max(nfds, fd2);
1028 nfds = max(nfds, fd1);
1032 nfds = max(nfds, fd2);
1035 r = select(nfds + 1, &rd, &wr, &er, NULL);
1037 if (r == \-1 && errno == EINTR)
1045 if (FD_ISSET(h, &rd)) {
1047 struct sockaddr_in client_address;
1049 memset(&client_address, 0, l = sizeof(client_address));
1050 r = accept(h, (struct sockaddr *) &client_address, &l);
1056 buf1_avail = buf1_written = 0;
1057 buf2_avail = buf2_written = 0;
1059 fd2 = connect_socket(forward_port, argv[3]);
1063 printf("connect from %s\\n",
1064 inet_ntoa(client_address.sin_addr));
1068 /* NB: read oob data before normal reads */
1071 if (FD_ISSET(fd1, &er)) {
1074 r = recv(fd1, &c, 1, MSG_OOB);
1078 send(fd2, &c, 1, MSG_OOB);
1081 if (FD_ISSET(fd2, &er)) {
1084 r = recv(fd2, &c, 1, MSG_OOB);
1088 send(fd1, &c, 1, MSG_OOB);
1091 if (FD_ISSET(fd1, &rd)) {
1092 r = read(fd1, buf1 + buf1_avail,
1093 BUF_SIZE \- buf1_avail);
1100 if (FD_ISSET(fd2, &rd)) {
1101 r = read(fd2, buf2 + buf2_avail,
1102 BUF_SIZE \- buf2_avail);
1109 if (FD_ISSET(fd1, &wr)) {
1110 r = write(fd1, buf2 + buf2_written,
1111 buf2_avail \- buf2_written);
1118 if (FD_ISSET(fd2, &wr)) {
1119 r = write(fd2, buf1 + buf1_written,
1120 buf1_avail \- buf1_written);
1127 /* check if write data has caught read data */
1129 if (buf1_written == buf1_avail)
1130 buf1_written = buf1_avail = 0;
1131 if (buf2_written == buf2_avail)
1132 buf2_written = buf2_avail = 0;
1134 /* one side has closed the connection, keep
1135 writing to the other side until empty */
1137 if (fd1 < 0 && buf1_avail \- buf1_written == 0)
1139 if (fd2 < 0 && buf2_avail \- buf2_written == 0)
1146 .\"O The above program properly forwards most kinds of TCP connections
1147 .\"O including OOB signal data transmitted by \fBtelnet\fP servers.
1148 .\"O It handles the tricky problem of having data flow in both directions
1149 .\"O simultaneously.
1150 .\"O You might think it more efficient to use a
1152 .\"O call and devote a thread to each stream.
1153 .\"O This becomes more tricky than you might suspect.
1154 .\"O Another idea is to set nonblocking I/O using
1156 .\"O This also has its problems because you end up using
1157 .\"O inefficient timeouts.
1158 上記のプログラムは、ほとんどの種類の TCP 接続をフォワードする。
1160 サーバによって中継される OOB シグナルデータも扱える。
1161 このプログラムは、データフローを双方向に同時に送るという、
1164 コールを使って、各ストリームごとに専用のスレッドを用いるほうが効率的だ、
1165 という人もいるかもしれない。しかし、これは考えているよりずっとややこしい。
1168 を使って非ブロック I/O をセットすれば良い、というアイデアもあるだろう。
1169 これにも実際には問題があり、タイムアウトが非効率的に起こってしまう。
1171 .\"O The program does not handle more than one simultaneous connection at a
1172 .\"O time, although it could easily be extended to do this with a linked list
1173 .\"O of buffers\(emone for each connection.
1174 .\"O At the moment, new
1175 .\"O connections cause the current connection to be dropped.
1176 このプログラムは一度にひとつ以上の同時接続を扱うことはできないが、
1177 その様に拡張するのは簡単で、バッファのリンクリストを
1179 現時点のものでは、新しい接続がくると古い接続は落ちてしまう。
1190 .BR sigprocmask (2),
1194 .BR sigemptyset (3),
1196 .BR sigismember (3),
1199 .\" This man page was written by Paul Sheer.