OSDN Git Service

(split) Convert release and draft pages to UTF-8.
[linuxjm/LDP_man-pages.git] / draft / man2 / select_tut.2
1 .\" This manpage is copyright (C) 2001 Paul Sheer.
2 .\"
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.
6 .\"
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.
11 .\"
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
18 .\" professionally.
19 .\"
20 .\" Formatted or processed versions of this manual, if unaccompanied by
21 .\" the source, must acknowledge the copyright and authors of this work.
22 .\"
23 .\" very minor changes, aeb
24 .\"
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
29 .\"
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
35 .\"
36 .\"WORD:        file descriptor         ファイルディスクリプタ
37 .\"WORD:        exceptional condition   例外状態
38 .\"
39 .TH SELECT_TUT 2 2010-06-10 "Linux" "Linux Programmer's Manual"
40 .\"O .SH NAME
41 .SH 名前
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 の多重化
45 .\"O .SH SYNOPSIS
46 .SH 書式
47 .nf
48 .\"O /* According to POSIX.1-2001 */
49 /* POSIX.1-2001 に従う場合 */
50 .br
51 .B #include <sys/select.h>
52 .sp
53 .\"O /* According to earlier standards */
54 /* 以前の規格に従う場合 */
55 .br
56 .B #include <sys/time.h>
57 .br
58 .B #include <sys/types.h>
59 .br
60 .B #include <unistd.h>
61 .sp
62 .BI "int select(int " nfds ", fd_set *" readfds ", fd_set *" writefds ,
63 .BI "           fd_set *" exceptfds ", struct timeval *" utimeout );
64 .sp
65 .BI "void FD_CLR(int " fd ", fd_set *" set );
66 .br
67 .BI "int  FD_ISSET(int " fd ", fd_set *" set );
68 .br
69 .BI "void FD_SET(int " fd ", fd_set *" set );
70 .br
71 .BI "void FD_ZERO(fd_set *" set );
72 .sp
73 .B #include <sys/select.h>
74 .sp
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 );
78 .fi
79 .sp
80 .in -4n
81 .\"O Feature Test Macro Requirements for glibc (see
82 .\"O .BR feature_test_macros (7)):
83 glibc 向けの機能検査マクロの要件
84 .RB ( feature_test_macros (7)
85 参照):
86 .in
87 .sp
88 .BR pselect ():
89 _POSIX_C_SOURCE\ >=\ 200112L || _XOPEN_SOURCE\ >=\ 600
90 .\"O .SH DESCRIPTION
91 .SH 説明
92 .\"O .BR select ()
93 .\"O (or
94 .\"O .BR pselect ())
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.
99 .BR select ()
100 (や
101 .BR pselect ())
102 を使うと、効率的に複数のファイルディスクリプタを監視し、
103 そのファイルディスクリプタのいずれかが
104 「ready (準備ができた)」状態、つまり I/O (入出力) が可能になっているかや、
105 ファイルディスクリプタのいずれかが
106 「例外状態 (exceptional condition)」が発生したか、を調べることができる。
107
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
113 .\"O .IR fd_set ,
114 .\"O and its contents can be manipulated with the macros
115 .\"O .BR FD_CLR (),
116 .\"O .BR FD_ISSET (),
117 .\"O .BR FD_SET (),
118 .\"O and
119 .\"O .BR FD_ZERO ().
120 .\"O A newly declared set should first be cleared using
121 .\"O .BR FD_ZERO ().
122 各々の集合は
123 .B fd_set
124 として宣言され、その内容は
125 .BR FD_CLR (),
126 .BR FD_ISSET (),
127 .BR FD_SET (),
128 .BR FD_ZERO ()
129 といったマクロによって操作できる。
130 新しく宣言された集合は、まず最初に
131 .BR FD_ZERO ()
132 を使ってクリアすべきである。
133 .\"O .BR select ()
134 .\"O modifies the contents of the sets according to the rules
135 .\"O described below; after calling
136 .\"O .BR select ()
137 .\"O you can test if a file descriptor is still present in a set with the
138 .\"O .BR FD_ISSET ()
139 .\"O macro.
140 .\"O .BR FD_ISSET ()
141 .\"O returns nonzero if a specified file descriptor is present in a set
142 .\"O and zero if it is not.
143 .\"O .BR FD_CLR ()
144 .\"O removes a file descriptor from a set.
145 .BR select ()
146 はこれらの集合の内容を、以降に述べる規則に従って修正する。
147 .BR select ()
148 を呼んだ後、ファイルディスクリプタがまだ集合に存在しているかどうかは、
149 .BR FD_ISSET ()
150 マクロによって調べることができる。
151 .BR FD_ISSET ()
152 は指定されたディスクリプタが集合に存在していれば 0 以外の値を返し、
153 存在しなければ 0 を返す。
154 .BR FD_CLR ()
155 は集合からのファイルディスクリプタの削除を行う。
156 .\"O .SS Arguments
157 .SS 引き数
158 .TP
159 \fIreadfds\fP
160 .\"O This set is watched to see if data is available for reading from any of
161 .\"O its file descriptors.
162 .\"O After
163 .\"O .BR select ()
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 データの読み込みが可能になったかどうかを監視する。
169 .BR select ()
170 から戻る時に、\fIreadfds\fP のうち、
171 直ちに読み込み可能なファイルディスクリプタ以外は
172 集合から削除される。
173 .TP
174 \fIwritefds\fP
175 .\"O This set is watched to see if there is space to write data to any of
176 .\"O its file descriptors.
177 .\"O After
178 .\"O .BR select ()
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 データを書き込むスペースがあるかどうかを監視する。
184 .BR select ()
185 から戻る時に、\fIwritefds\fP のうち、
186 直ちに書き込み可能なファイルディスクリプタ以外は
187 集合から削除される。
188 .TP
189 \fIexceptfds\fP
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.
194 .\"O See
195 .\"O .BR recv (2),
196 .\"O .BR send (2),
197 .\"O and
198 .\"O .BR tcp (7)
199 .\"O for more details about OOB data.
200 .\"O (One other less common case where
201 .\"O .BR select (2)
202 .\"O indicates an exceptional condition occurs with pseudoterminals
203 .\"O in packet mode; see
204 .\"O .BR tty_ioctl (4).)
205 .\"O After
206 .\"O .BR select ()
207 .\"O has returned,
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 データが
214 読み込み可能な場合である。
215 OOB データの詳細については、
216 .BR recv (2),
217 .BR send (2),
218 .BR tcp (7)
219 を参照のこと。
220 (これ以外では、まれなことだが、
221 パケットモードの擬似端末 (pseudoterminals) で
222 .BR select ()
223 が例外状態を示すことがある。)
224 .BR select ()
225 が返る時に、\fIexceptfds\fP のうち、
226 例外状態が発生したディスクリプタ以外は集合から削除される。
227 .TP
228 \fInfds\fP
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 として渡さないといけない、ということだ。
239 .TP
240 \fIutimeout\fP
241 .\"O This is the longest time
242 .\"O .BR select ()
243 .\"O may wait before returning, even if nothing interesting happened.
244 .\"O If this value is passed as NULL, then
245 .\"O .BR select ()
246 .\"O blocks indefinitely waiting for a file descriptor to become ready.
247 .\"O \fIutimeout\fP can be set to zero seconds, which causes
248 .\"O .BR select ()
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:
252 (何も起こらなかった場合に)
253 .BR select ()
254 が戻る前に待つ最大時間である。
255 この値に NULL を渡すと、
256 .BR select ()
257 はファイルディスクリプタのいずれかが ready (準備ができた) 状態に
258 なるまで待ち続けてずっと停止する。
259 \fIutimeout\fP は 0 秒にすることもでき、
260 この場合
261 .BR select ()
262 は直ちに返り、呼び出し時点のファイルディスクリプタの状態に
263 関する情報が返される。
264 構造体 \fIstruct timeval\fP は次のように定義されている:
265 .IP
266 .in +4n
267 .nf
268 struct timeval {
269     time_t tv_sec;    /* seconds */
270     long tv_usec;     /* microseconds */
271 };
272 .fi
273 .in
274 .TP
275 \fIntimeout\fP
276 .\"O This argument for
277 .\"O .BR pselect ()
278 .\"O has the same meaning as
279 .\"O .IR utimeout ,
280 .\"O but
281 .\"O .I "struct timespec"
282 .\"O has nanosecond precision as follows:
283 .BR pselect ()
284 のこの引き数は
285 .I utimeout
286 と同じ意味を持つが、
287 .I "struct timespec"
288 は次に示すようにナノ秒の精度を持つ。
289 .in +4n
290 .nf
291 struct timespec {
292     long tv_sec;    /* seconds */
293     long tv_nsec;   /* nanoseconds */
294 };
295 .fi
296 .in
297 .TP
298 \fIsigmask\fP
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
302 .\"O .BR pselect ()
303 .\"O call (see
304 .\"O .BR sigaddset (3)
305 .\"O and
306 .\"O .BR sigprocmask (2)).
307 .\"O It may be NULL,
308 .\"O in which case the call does not modify the signal mask on
309 .\"O entry and exit to the function.
310 .\"O In this case,
311 .\"O .BR pselect ()
312 .\"O will then behave just like
313 .\"O .BR select ().
314 この引き数は、呼び出し側が
315 .BR pselect ()
316 内部で停止している間に、カーネルが通知を許可すべきシグナル集合
317 (すなわち、呼び出したスレッドのシグナルマスクから削除すべきシグナル集合)
318 を保持する
319 .RB ( sigaddset (3)
320
321 .BR sigprocmask (2)
322 を参照)。
323 この引き数は NULL にすることもでき、その場合はこの関数へ
324 入るとき・出るときにシグナルマスクを変更しない。
325 この場合、
326 .BR pselect ()
327
328 .BR select ()
329 と全く同じ動作となる。
330 .\"O .SS Combining Signal and Data Events
331 .SS シグナルとデータイベントを組み合わせる
332 .\"O .BR pselect ()
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 可能な状態になるのと同時に
340 シグナルも待ちたい場合には、
341 .BR pselect ()
342 が便利である。
343 シグナルを受信するプログラムは、通常は、
344 シグナルハンドラをグローバルなフラグを立てるためだけに使う。
345 このグローバルなフラグは、
346 そのイベントをプログラムのメインループで
347 処理しなければならないことを示す。
348 .\"O A signal will cause the
349 .\"O .BR select ()
350 .\"O (or
351 .\"O .BR pselect ())
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
355 .\"O .BR select ()
356 .\"O would block indefinitely.
357 シグナルを受けると
358 .BR select ()
359 (や
360 .BR pselect ())
361
362 \fIerrno\fP に \fBEINTR\fP をセットして戻ることになる。
363 シグナルがプログラムのメインループで処理されるためにはこの動作が不可欠で、
364 これがないと
365 .BR select ()
366 は永遠に停止し続けることになる。
367 .\"O Now, somewhere
368 .\"O in the main loop will be a conditional to check the global flag.
369 .\"O So we must ask:
370 .\"O what if a signal arrives after the conditional, but before the
371 .\"O .BR select ()
372 .\"O call?
373 .\"O The answer is that
374 .\"O .BR select ()
375 .\"O would block indefinitely, even though an event is actually pending.
376 さて、メインループのどこかにこのグローバルフラグをチェックする
377 条件文があるとしよう。ここで少し考えてみないといけない。
378 「シグナルが条件文の後、しかし
379 .BR select ()
380 コールの前に到着したら
381 どうなるのか?」
382 答えは「その
383 .BR select ()
384 は、たとえ解決待ちのイベントがあったとしても、
385 永遠に停止する」である。
386 .\"O This race condition is solved by the
387 .\"O .BR pselect ()
388 .\"O call.
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
391 .\"O .BR pselect ()
392 .\"O call.
393 この競合状態は
394 .BR pselect ()
395 コールによって解決できる。
396 このコールを使うと、
397 .BR pselect ()
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).
404 .\"O Our
405 .\"O .BR pselect ()
406 .\"O call would enable
407 .\"O .B SIGCHLD
408 .\"O by using an empty signal mask.
409 .\"O Our program would look like:
410 例えば、問題となっているイベントが子プロセスの終了の場合を考えよう。
411 メインループが始まる前に、
412 .B SIGCHLD
413
414 .BR sigprocmask (2)
415 でブロックする。
416 .BR pselect ()
417 コールでは
418 .B SIGCHLD
419 を、もともとのシグナルマスクを使って有効にするのだ。
420 このプログラムは次のようになる。
421 .PP
422 .nf
423 static volatile sig_atomic_t got_SIGCHLD = 0;
424
425 static void
426 child_sig_handler(int sig)
427 {
428     got_SIGCHLD = 1;
429 }
430
431 int
432 main(int argc, char *argv[])
433 {
434     sigset_t sigmask, empty_mask;
435     struct sigaction sa;
436     fd_set readfds, writefds, exceptfds;
437     int r;
438
439     sigemptyset(&sigmask);
440     sigaddset(&sigmask, SIGCHLD);
441     if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
442         perror("sigprocmask");
443         exit(EXIT_FAILURE);
444     }
445
446     sa.sa_flags = 0;
447     sa.sa_handler = child_sig_handler;
448     sigemptyset(&sa.sa_mask);
449     if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
450         perror("sigaction");
451         exit(EXIT_FAILURE);
452     }
453
454     sigemptyset(&empty_mask);
455
456     for (;;) {          /* main loop */
457         /* Initialize readfds, writefds, and exceptfds
458            before the pselect() call. (Code omitted.) */
459
460         r = pselect(nfds, &readfds, &writefds, &exceptfds,
461                     NULL, &empty_mask);
462         if (r == \-1 && errno != EINTR) {
463             /* Handle error */
464         }
465
466         if (got_SIGCHLD) {
467             got_SIGCHLD = 0;
468
469             /* Handle signalled event here; e.g., wait() for all
470                terminated children. (Code omitted.) */
471         }
472
473         /* main body of program */
474     }
475 }
476 .fi
477 .\"O .SS Practical
478 .SS 実例
479 .\"O So what is the point of
480 .\"O .BR select ()?
481 .\"O Can't I just read and write to my descriptors whenever I want?
482 .\"O The point of
483 .\"O .BR select ()
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
491 .\"O .BR read (2)
492 .\"O and
493 .\"O .BR write (2)
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.
497 .\"O .BR select ()
498 .\"O efficiently copes with this situation.
499 実際のところ
500 .BR select ()
501 の大事な点は何なのか?
502 ディスクリプタは好きなときに読み書きできるんじゃないの?
503 .BR select ()
504 の重要なところは、複数のディスクリプタを同時に監視でき、
505 なんの動きもなければプロセスを適切にスリープ状態に移行するところにあるのだ。
506 UNIX プログラマは、
507 複数のファイルディスクリプタの入出力を同時に扱わねばならず、
508 しかもデータの流れは間欠的である、という状況によく出会う。
509 単に
510 .BR read (2)
511
512 .BR write (2)
513 コールのシーケンスを作るだけでは、それらのコールのどれかが
514 ファイルディスクリプタからのデータを待ってブロックしており、
515 別のファイルディスクリプタには I/O が可能なのに使えない、
516 ということになってしまうだろう。
517 .BR select ()
518 を使うとこの状況に効果的に対処できる。
519 .\"O .SS Select Law
520 .SS SELECT の掟
521 .\"O Many people who try to use
522 .\"O .BR select ()
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
530 .\"O .BR select (),
531 .\"O so here is a list of essentials to watch for when using
532 .\"O .BR select ().
533 .BR select ()
534 を使おうとした多くの人は、理解しにくい挙動に出くわし、結果的に
535 できたものは移植性がないか、よくてもギリギリのものになってしまう。
536 例えば、上記のプログラムは、
537 集合に含まれるファイルディスクリプタを非停止 (nonblocking) モード
538 にしなくても、どこにもブロックが生じないよう注意して書かれている。
539 微妙な間違いによって、
540 .BR select ()
541 を使う利点は簡単に失われてしまう。
542 そこで、
543 .BR select ()
544 コールを使うときに注意すべき重要事項を列挙しておくことにする。
545 .TP 4
546 1.
547 .\"O You should always try to use
548 .\"O .BR select ()
549 .\"O without a timeout.
550 .\"O Your program
551 .\"O should have nothing to do if there is no data available.
552 .\"O Code that
553 .\"O depends on timeouts is not usually portable and is difficult to debug.
554 .BR select ()
555 を使うときは、タイムアウトは設定すべきでない。
556 処理するデータが無いときには、
557 あなたのプログラムには何もすることは無いはずである。
558 タイムアウトに依存したコードは通常移植性がなく、
559 デバッグも難しくなる。
560 .TP
561 2.
562 .\"O The value \fInfds\fP must be properly calculated for efficiency as
563 .\"O explained above.
564 上述したように、
565 効率的なプログラムを書くには
566 .I nfds
567 の値を適切に計算して与えなければならない。
568 .TP
569 3.
570 .\"O No file descriptor must be added to any set if you do not intend
571 .\"O to check its result after the
572 .\"O .BR select ()
573 .\"O call, and respond appropriately.
574 .\"O See next rule.
575 .BR select ()
576 コールの終了後に結果をチェックして、
577 適切に対応するつもりのないファイルディスクリプタは、
578 どの集合にも加えてはならない。
579 次のルールも参照。
580 .TP
581 4.
582 .\"O After
583 .\"O .BR select ()
584 .\"O returns, all file descriptors in all sets
585 .\"O should be checked to see if they are ready.
586 .BR select ()
587 から返った後には、全ての集合の全てのファイルディスクリプタについて
588 読み書き可能な状態になっているかをチェックすべきである。
589 .TP
590 5.
591 .\"O The functions
592 .\"O .BR read (2),
593 .\"O .BR recv (2),
594 .\"O .BR write (2),
595 .\"O and
596 .\"O .BR send (2)
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.
604 .BR read (2),
605 .BR recv (2),
606 .BR write (2),
607 .BR send (2)
608 といった関数は、こちらが要求した全データを読み書きする必要は\fIない\fP。
609 もし全データを読み書きするなら、それはトラフィックの負荷が小さく、
610 ストリームが速い場合だろう。この条件は常に満たされるとは限らない。
611 これらの関数が頑張っても 1 バイトしか送受信できないような場合も
612 考慮に入れてやらなければならない。
613 .TP
614 6.
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.
617 .\"O It is extremely
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 バイトにしているが、
625 このサイズを大きくするのは簡単だろう。
626 .TP
627 7.
628 .\"O The functions
629 .\"O .BR read (2),
630 .\"O .BR recv (2),
631 .\"O .BR write (2),
632 .\"O and
633 .\"O .BR send (2)
634 .\"O as well as the
635 .\"O .BR select ()
636 .\"O call can return \-1 with
637 .\"O .I errno
638 .\"O set to \fBEINTR\fP,
639 .\"O or with
640 .\"O .I errno
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.
648 .BR read (2),
649 .BR recv (2),
650 .BR write (2),
651 .BR send (2)
652 などの関数や
653 .BR select ()
654 コールは、
655 .I errno
656
657 .B EINTR " や " EAGAIN
658 .RB ( EWOULDBLOCK )
659 にして \-1 を返すことがある。
660 このような結果に対して適切に対応してやらなければならない
661 (上記の例ではしていない)。
662 書いているプログラムがシグナルを受ける予定がなければ、
663 .B EINTR
664 が返されることはあまり考えられない。
665 書いているプログラムで非ブロック I/O をセットしていない場合は、
666 .B EAGAIN
667 が返されることはないだろう。
668 .\" それでもなお、完全を期するならば、
669 .\" これらのエラーを考慮に入れる必要がある。
670 .TP
671 8.
672 .\"O Never call
673 .\"O .BR read (2),
674 .\"O .BR recv (2),
675 .\"O .BR write (2),
676 .\"O or
677 .\"O .BR send (2)
678 .\"O with a buffer length of zero.
679 決して、引き数に長さ 0 のバッファを指定して
680 .BR read (2),
681 .BR recv (2),
682 .BR write (2),
683 .BR send (2)
684 を呼び出してはならない。
685 .TP
686 9.
687 .\"O If the functions
688 .\"O .BR read (2),
689 .\"O .BR recv (2),
690 .\"O .BR write (2),
691 .\"O and
692 .\"O .BR send (2)
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
696 .\"O .BR select ()
697 .\"O again.
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.
701 .BR read (2),
702 .BR recv (2),
703 .BR write (2),
704 .BR send (2)
705
706 \fB7.\fP に示した以外のエラーで失敗した場合や、
707 入力系の関数の一つがファイル末尾を表す 0 を返した場合は、
708 そのディスクリプタをもう一度 select に渡しては\fIならない\fP。
709 下記の例では、そのディスクリプタをただちにクローズし、
710 そこには \-1 をセットして、
711 それが集合に含まれ続けるのを許さないようにしている。
712 .TP
713 10.
714 .\"O The timeout value must be initialized with each new call to
715 .\"O .BR select (),
716 .\"O since some operating systems modify the structure.
717 .\"O .BR pselect ()
718 .\"O however does not modify its timeout structure.
719 タイムアウトの値は
720 .BR select ()
721 を呼ぶたびに初期化すべきである。
722 OS によっては timeout 構造体が変更される場合があるからである。
723 但し、
724 .BR pselect ()
725 は自分の timeout 構造体を変更することはない。
726 .TP
727 11.
728 .\"O Since
729 .\"O .BR select ()
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.
733 .BR select ()
734 はファイルディスクリプタ集合を変更するので、
735 .BR select ()
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.
740 .\" .TP
741 .\"O .\" 11.
742 .\"O .\" I have heard that the Windows socket layer does not cope with OOB data
743 .\"O .\" properly.
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 .\" また、ファイルディスクリプタが全くセットされていないような
753 .\" .BR select ()
754 .\" コールも正しく処理しないらしい。
755 .\" ファイルディスクリプタを一切設定しないで timeout を使うやり方は、
756 .\" 1 秒以下の精度でプロセスをスリープさせるには便利な方法なのだが
757 .\" (続きを見よ)。
758 .\"O .SS Usleep Emulation
759 .SS usleep エミュレーション
760 .\"O On systems that do not have a
761 .\"O .BR usleep (3)
762 .\"O function, you can call
763 .\"O .BR select ()
764 .\"O with a finite timeout and no file descriptors as
765 .\"O follows:
766 .BR usleep (3)
767 関数を持たないシステムでは、
768 有限のタイムアウトを指定し、ファイルディスクリプタを全くセットせずに
769 .BR select ()
770 を呼び出すことで、これを代用できる。
771 以下のようにする。
772 .PP
773 .nf
774     struct timeval tv;
775     tv.tv_sec = 0;
776     tv.tv_usec = 200000;  /* 0.2 seconds */
777     select(0, NULL, NULL, NULL, &tv);
778 .fi
779 .PP
780 .\"O This is only guaranteed to work on UNIX systems, however.
781 但し、これが動くと保証されているのは UNIX システムに限られる。
782 .\"O .SH RETURN VALUE
783 .SH 返り値
784 .\"O On success,
785 .\"O .BR select ()
786 .\"O returns the total number of file descriptors
787 .\"O still present in the file descriptor sets.
788 成功すると、
789 .BR select ()
790 はファイルディスクリプタ集合に残っている
791 ファイルディスクリプタの総数を返す。
792
793 .\"O If
794 .\"O .BR select ()
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).
798 .BR select ()
799 がタイムアウトすると、返り値は 0 になる。
800 その時、ファイルディスクリプタ集合はすべて空である
801 (しかしそうならないシステムもある)。
802
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.
807 .\"O .BR pselect ()
808 .\"O however never modifies \fIntimeout\fP.
809 返り値が \-1 の場合はエラーを意味し、
810 .I errno
811 が適切にセットされる。エラーが起こった場合、
812 返された集合の内容や構造体 \fIstruct timeout\fP の内容は
813 未定義となっており、使用すべきではない。
814 しかし
815 .BR pselect ()
816 は決して
817 .I ntimeout
818 を変更しない。
819 .\"O .SH NOTES
820 .SH 注意
821 .\"O Generally speaking,
822 .\"O all operating systems that support sockets also support
823 .\"O .BR select ().
824 .\"O .BR select ()
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 一般的に言って、ソケットをサポートする全てのオペレーティングシステムは
830 .BR select ()
831 もサポートしている。
832 .BR select ()
833 を使うと、プログラマがスレッド、フォーク、IPC、シグナル、メモリ共有、
834 等々を使ってもっと複雑な方法で解決しようとする多くの問題が、
835 移植性がありかつ効率的な方法で解決できる。
836 .PP
837 .\"O The
838 .\"O .BR poll (2)
839 .\"O system call has the same functionality as
840 .\"O .BR select (),
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
844 .\"O .BR select ().
845 .BR poll (2)
846 システムコールは
847 .BR select ()
848 と同じ機能を持っており、
849 まばらなファイルディスクリプタ集合を監視する場合に
850 いくらか効率がよい。
851 現在では広く利用可能であるが、以前は
852 .BR select ()
853 より移植性の面で劣っていた。
854 .PP
855 .\"O The Linux-specific
856 .\"O .BR epoll (7)
857 .\"O API provides an interface that is more efficient than
858 .\"O .BR select (2)
859 .\"O and
860 .\"O .BR poll (2)
861 .\"O when monitoring large numbers of file descriptors.
862 Linux 独自の
863 .BR epoll (7)
864 API は、多数のファイルディスクリプタを監視する場合に
865 .BR select (2)
866
867 .BR poll (2)
868 よりも効率的なインタフェースを提供している。
869 .\"O .SH EXAMPLE
870 .SH 例
871 .\"O Here is an example that better demonstrates the true utility of
872 .\"O .BR select ().
873 .\"O The listing below a TCP forwarding program that forwards
874 .\"O from one TCP port to another.
875 .BR select ()
876 の本当に便利な点を示す、よい例を紹介する。
877 以下のリストは、ある TCP ポートから別のポートへ転送を行う
878 TCP フォワードプログラムである。
879 .PP
880 .nf
881 #include <stdlib.h>
882 #include <stdio.h>
883 #include <unistd.h>
884 #include <sys/time.h>
885 #include <sys/types.h>
886 #include <string.h>
887 #include <signal.h>
888 #include <sys/socket.h>
889 #include <netinet/in.h>
890 #include <arpa/inet.h>
891 #include <errno.h>
892
893 static int forward_port;
894
895 #undef max
896 #define max(x,y) ((x) > (y) ? (x) : (y))
897
898 static int
899 listen_socket(int listen_port)
900 {
901     struct sockaddr_in a;
902     int s;
903     int yes;
904
905     if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
906         perror("socket");
907         return \-1;
908     }
909     yes = 1;
910     if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
911             (char *) &yes, sizeof(yes)) == \-1) {
912         perror("setsockopt");
913         close(s);
914         return \-1;
915     }
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) {
920         perror("bind");
921         close(s);
922         return \-1;
923     }
924     printf("accepting connections on port %d\\n", listen_port);
925     listen(s, 10);
926     return s;
927 }
928
929 static int
930 connect_socket(int connect_port, char *address)
931 {
932     struct sockaddr_in a;
933     int s;
934
935     if ((s = socket(AF_INET, SOCK_STREAM, 0)) == \-1) {
936         perror("socket");
937         close(s);
938         return \-1;
939     }
940
941     memset(&a, 0, sizeof(a));
942     a.sin_port = htons(connect_port);
943     a.sin_family = AF_INET;
944
945     if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
946         perror("bad IP address format");
947         close(s);
948         return \-1;
949     }
950
951     if (connect(s, (struct sockaddr *) &a, sizeof(a)) == \-1) {
952         perror("connect()");
953         shutdown(s, SHUT_RDWR);
954         close(s);
955         return \-1;
956     }
957     return s;
958 }
959
960 #define SHUT_FD1 do {                                \\
961                      if (fd1 >= 0) {                 \\
962                          shutdown(fd1, SHUT_RDWR);   \\
963                          close(fd1);                 \\
964                          fd1 = \-1;                   \\
965                      }                               \\
966                  } while (0)
967
968 #define SHUT_FD2 do {                                \\
969                      if (fd2 >= 0) {                 \\
970                          shutdown(fd2, SHUT_RDWR);   \\
971                          close(fd2);                 \\
972                          fd2 = \-1;                   \\
973                      }                               \\
974                  } while (0)
975
976 #define BUF_SIZE 1024
977
978 int
979 main(int argc, char *argv[])
980 {
981     int h;
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;
986
987     if (argc != 4) {
988         fprintf(stderr, "Usage\\n\\tfwd <listen-port> "
989                  "<forward-to-port> <forward-to-ip-address>\\n");
990         exit(EXIT_FAILURE);
991     }
992
993     signal(SIGPIPE, SIG_IGN);
994
995     forward_port = atoi(argv[2]);
996
997     h = listen_socket(atoi(argv[1]));
998     if (h == \-1)
999         exit(EXIT_FAILURE);
1000
1001     for (;;) {
1002         int r, nfds = 0;
1003         fd_set rd, wr, er;
1004
1005         FD_ZERO(&rd);
1006         FD_ZERO(&wr);
1007         FD_ZERO(&er);
1008         FD_SET(h, &rd);
1009         nfds = max(nfds, h);
1010         if (fd1 > 0 && buf1_avail < BUF_SIZE) {
1011             FD_SET(fd1, &rd);
1012             nfds = max(nfds, fd1);
1013         }
1014         if (fd2 > 0 && buf2_avail < BUF_SIZE) {
1015             FD_SET(fd2, &rd);
1016             nfds = max(nfds, fd2);
1017         }
1018         if (fd1 > 0 && buf2_avail \- buf2_written > 0) {
1019             FD_SET(fd1, &wr);
1020             nfds = max(nfds, fd1);
1021         }
1022         if (fd2 > 0 && buf1_avail \- buf1_written > 0) {
1023             FD_SET(fd2, &wr);
1024             nfds = max(nfds, fd2);
1025         }
1026         if (fd1 > 0) {
1027             FD_SET(fd1, &er);
1028             nfds = max(nfds, fd1);
1029         }
1030         if (fd2 > 0) {
1031             FD_SET(fd2, &er);
1032             nfds = max(nfds, fd2);
1033         }
1034
1035         r = select(nfds + 1, &rd, &wr, &er, NULL);
1036
1037         if (r == \-1 && errno == EINTR)
1038             continue;
1039
1040         if (r == \-1) {
1041             perror("select()");
1042             exit(EXIT_FAILURE);
1043         }
1044
1045         if (FD_ISSET(h, &rd)) {
1046             unsigned int l;
1047             struct sockaddr_in client_address;
1048
1049             memset(&client_address, 0, l = sizeof(client_address));
1050             r = accept(h, (struct sockaddr *) &client_address, &l);
1051             if (r == \-1) {
1052                 perror("accept()");
1053             } else {
1054                 SHUT_FD1;
1055                 SHUT_FD2;
1056                 buf1_avail = buf1_written = 0;
1057                 buf2_avail = buf2_written = 0;
1058                 fd1 = r;
1059                 fd2 = connect_socket(forward_port, argv[3]);
1060                 if (fd2 == \-1)
1061                     SHUT_FD1;
1062                 else
1063                     printf("connect from %s\\n",
1064                             inet_ntoa(client_address.sin_addr));
1065             }
1066         }
1067
1068         /* NB: read oob data before normal reads */
1069
1070         if (fd1 > 0)
1071             if (FD_ISSET(fd1, &er)) {
1072                 char c;
1073
1074                 r = recv(fd1, &c, 1, MSG_OOB);
1075                 if (r < 1)
1076                     SHUT_FD1;
1077                 else
1078                     send(fd2, &c, 1, MSG_OOB);
1079             }
1080         if (fd2 > 0)
1081             if (FD_ISSET(fd2, &er)) {
1082                 char c;
1083
1084                 r = recv(fd2, &c, 1, MSG_OOB);
1085                 if (r < 1)
1086                     SHUT_FD2;
1087                 else
1088                     send(fd1, &c, 1, MSG_OOB);
1089             }
1090         if (fd1 > 0)
1091             if (FD_ISSET(fd1, &rd)) {
1092                 r = read(fd1, buf1 + buf1_avail,
1093                           BUF_SIZE \- buf1_avail);
1094                 if (r < 1)
1095                     SHUT_FD1;
1096                 else
1097                     buf1_avail += r;
1098             }
1099         if (fd2 > 0)
1100             if (FD_ISSET(fd2, &rd)) {
1101                 r = read(fd2, buf2 + buf2_avail,
1102                           BUF_SIZE \- buf2_avail);
1103                 if (r < 1)
1104                     SHUT_FD2;
1105                 else
1106                     buf2_avail += r;
1107             }
1108         if (fd1 > 0)
1109             if (FD_ISSET(fd1, &wr)) {
1110                 r = write(fd1, buf2 + buf2_written,
1111                            buf2_avail \- buf2_written);
1112                 if (r < 1)
1113                     SHUT_FD1;
1114                 else
1115                     buf2_written += r;
1116             }
1117         if (fd2 > 0)
1118             if (FD_ISSET(fd2, &wr)) {
1119                 r = write(fd2, buf1 + buf1_written,
1120                            buf1_avail \- buf1_written);
1121                 if (r < 1)
1122                     SHUT_FD2;
1123                 else
1124                     buf1_written += r;
1125             }
1126
1127         /* check if write data has caught read data */
1128
1129         if (buf1_written == buf1_avail)
1130             buf1_written = buf1_avail = 0;
1131         if (buf2_written == buf2_avail)
1132             buf2_written = buf2_avail = 0;
1133
1134         /* one side has closed the connection, keep
1135            writing to the other side until empty */
1136
1137         if (fd1 < 0 && buf1_avail \- buf1_written == 0)
1138             SHUT_FD2;
1139         if (fd2 < 0 && buf2_avail \- buf2_written == 0)
1140             SHUT_FD1;
1141     }
1142     exit(EXIT_SUCCESS);
1143 }
1144 .fi
1145 .PP
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
1151 .\"O .BR fork (2)
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
1155 .\"O .BR fcntl (2).
1156 .\"O This also has its problems because you end up using
1157 .\"O inefficient timeouts.
1158 上記のプログラムは、ほとんどの種類の TCP 接続をフォワードする。
1159 .B telnet
1160 サーバによって中継される OOB シグナルデータも扱える。
1161 このプログラムは、データフローを双方向に同時に送るという、
1162 ややこしい問題も処理できる。
1163 .BR fork (2)
1164 コールを使って、各ストリームごとに専用のスレッドを用いるほうが効率的だ、
1165 という人もいるかもしれない。しかし、これは考えているよりずっとややこしい。
1166 あるいは、
1167 .BR fcntl (2)
1168 を使って非ブロック I/O をセットすれば良い、というアイデアもあるだろう。
1169 これにも実際には問題があり、タイムアウトが非効率的に起こってしまう。
1170
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 その様に拡張するのは簡単で、バッファのリンクリストを
1178 (接続ごとにひとつずつ) 使えばよい。
1179 現時点のものでは、新しい接続がくると古い接続は落ちてしまう。
1180 .\"O .SH SEE ALSO
1181 .SH 関連項目
1182 .BR accept (2),
1183 .BR connect (2),
1184 .BR ioctl (2),
1185 .BR poll (2),
1186 .BR read (2),
1187 .BR recv (2),
1188 .BR select (2),
1189 .BR send (2),
1190 .BR sigprocmask (2),
1191 .BR write (2),
1192 .BR sigaddset (3),
1193 .BR sigdelset (3),
1194 .BR sigemptyset (3),
1195 .BR sigfillset (3),
1196 .BR sigismember (3),
1197 .BR epoll (7)
1198 .\" .SH AUTHORS
1199 .\" This man page was written by Paul Sheer.