File: select_tut.2

package info (click to toggle)
manpages-ja 0.5.0.0.20221215%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 29,304 kB
  • sloc: perl: 161; makefile: 61
file content (504 lines) | stat: -rw-r--r-- 22,150 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
.\" This manpage is copyright (C) 2001 Paul Sheer.
.\"
.\" %%%LICENSE_START(VERBATIM)
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one.
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date.  The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein.  The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\" %%%LICENSE_END
.\"
.\" very minor changes, aeb
.\"
.\" Modified 5 June 2002, Michael Kerrisk <mtk.manpages@gmail.com>
.\" 2006-05-13, mtk, removed much material that is redundant with select.2
.\"             various other changes
.\" 2008-01-26, mtk, substantial changes and rewrites
.\"
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.\"
.\" Translated 2002-02-21, NAKANO Takeo <nakano@apm.seikei.ac.jp>
.\" Updated 2002-09-23, Akihiro MOTOKI <amotoki@dd.iij4u.or.jp>
.\" Updated 2005-03-15, Akihiro MOTOKI <amotoki@dd.iij4u.or.jp>
.\" Updated 2006-07-21, Akihiro MOTOKI, LDP v2.36
.\" Updated 2009-02-13, Akihiro MOTOKI, LDP v3.18
.\"
.TH SELECT_TUT 2 2020\-04\-11 Linux "Linux Programmer's Manual"
.SH 名前
select, pselect \- 同期 I/O の多重化
.SH 書式
\fBselect\fP(2)  参照。
.SH 説明
システムコール \fBselect\fP() や \fBpselect\fP() を使うと、効率的に複数のファイルディスクリプターを監視し、
そのファイルディスクリプターのいずれかが 「ready (準備ができた)」状態、つまり I/O (入出力) が可能になっているかや、
ファイルディスクリプターのいずれかが 「例外状態 (exceptional condition)」が発生したか、を調べることができる。
.PP
.\"
This page provides background and tutorial information on the use of these
system calls.  For details of the arguments and semantics of \fBselect\fP()
and \fBpselect\fP(), see \fBselect\fP(2).
.SS シグナルとデータイベントを組み合わせる
ファイルディスクリプターが I/O 可能な状態になるのと同時に シグナルも待ちたい場合には、 \fBpselect\fP()  が便利である。
シグナルを受信するプログラムは、通常は、 シグナルハンドラーをグローバルなフラグを立てるためだけに使う。 このグローバルなフラグは、
そのイベントをプログラムのメインループで 処理しなければならないことを示す。 シグナルを受けると \fBselect\fP()  (や
\fBpselect\fP())  は \fIerrno\fP に \fBEINTR\fP をセットして戻ることになる。
シグナルがプログラムのメインループで処理されるためにはこの動作が不可欠で、 これがないと \fBselect\fP()  は永遠に停止し続けることになる。
.PP
さて、メインループのどこかにこのグローバルフラグをチェックする 条件文があるとしよう。ここで少し考えてみないといけない。 「シグナルが条件文の後、しかし
\fBselect\fP()  コールの前に到着したら どうなるのか?」 答えは「その \fBselect\fP()
は、たとえ解決待ちのイベントがあったとしても、 永遠に停止する」である。 この競合状態は \fBpselect\fP()  コールによって解決できる。
このコールを使うと、 \fBpselect\fP() でのみ受信したいシグナルの集合をシグナルマスクに設定することができる。
例えば、問題となっているイベントが子プロセスの終了の場合を考えよう。 メインループが始まる前に、 \fBSIGCHLD\fP を
\fBsigprocmask\fP(2)  でブロックする。 \fBpselect\fP()  コールでは \fBSIGCHLD\fP
を、もともとのシグナルマスクを使って有効にするのだ。 このプログラムは次のようになる。
.PP
.EX
static volatile sig_atomic_t got_SIGCHLD = 0;

static void
child_sig_handler(int sig)
{
    got_SIGCHLD = 1;
}

int
main(int argc, char *argv[])
{
    sigset_t sigmask, empty_mask;
    struct sigaction sa;
    fd_set readfds, writefds, exceptfds;
    int r;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGCHLD);
    if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == \-1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    sa.sa_flags = 0;
    sa.sa_handler = child_sig_handler;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGCHLD, &sa, NULL) == \-1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    sigemptyset(&empty_mask);

    for (;;) {          /* main loop */
        /* Initialize readfds, writefds, and exceptfds
           before the pselect() call. (Code omitted.) */

        r = pselect(nfds, &readfds, &writefds, &exceptfds,
                    NULL, &empty_mask);
        if (r == \-1 && errno != EINTR) {
            /* Handle error */
        }

        if (got_SIGCHLD) {
            got_SIGCHLD = 0;

            /* Handle signalled event here; e.g., wait() for all
               terminated children. (Code omitted.) */
        }

        /* main body of program */
    }
}
.EE
.SS 実例
実際のところ \fBselect\fP()  の大事な点は何なのか? ファイルディスクリプターは好きなときに読み書きできるんじゃないの?
\fBselect\fP()  の重要なところは、複数のディスクリプターを同時に監視でき、
なんの動きもなければプロセスを適切にスリープ状態に移行するところにあるのだ。 UNIX プログラマは、
複数のファイルディスクリプターの入出力を同時に扱わねばならず、 しかもデータの流れは間欠的である、という状況によく出会う。 単に \fBread\fP(2)
や \fBwrite\fP(2)  コールのシーケンスを作るだけでは、それらのコールのどれかが ファイルディスクリプターからのデータを待ってブロックしており、
別のファイルディスクリプターには I/O が可能なのに使えない、 ということになってしまうだろう。 \fBselect\fP()
を使うとこの状況に効果的に対処できる。
.SS "SELECT の掟"
\fBselect\fP()  を使おうとした多くの人は、理解しにくい挙動に出くわし、結果的に
できたものは移植性がないか、よくてもギリギリのものになってしまう。 例えば、上記のプログラムは、 集合に含まれるファイルディスクリプターを非停止
(nonblocking) モード にしなくても、どこにもブロックが生じないよう注意して書かれている。 微妙な間違いによって、 \fBselect\fP()
を使う利点は簡単に失われてしまう。 そこで、 \fBselect\fP()  コールを使うときに注意すべき重要事項を列挙しておくことにする。
.TP  4
1.
\fBselect\fP()  を使うときは、タイムアウトは設定すべきでない。 処理するデータが無いときには、
あなたのプログラムには何もすることは無いはずである。 タイムアウトに依存したコードは通常移植性がなく、 デバッグも難しくなる。
.TP 
2.
上述したように、 効率的なプログラムを書くには \fInfds\fP の値を適切に計算して与えなければならない。
.TP 
3.
\fBselect\fP()  コールの終了後に結果をチェックして、 適切に対応するつもりのないファイルディスクリプターは、 どの集合にも加えてはならない。
次のルールも参照。
.TP 
4.
\fBselect\fP()  から返った後には、全ての集合の全てのファイルディスクリプターについて 読み書き可能な状態になっているかをチェックすべきである。
.TP 
5.
\fBread\fP(2), \fBrecv\fP(2), \fBwrite\fP(2), \fBsend\fP(2)
といった関数は、こちらが要求した全データを読み書きする必要は\fIない\fP。 もし全データを読み書きするなら、それはトラフィックの負荷が小さく、
ストリームが速い場合だろう。この条件は常に満たされるとは限らない。 これらの関数が頑張っても 1 バイトしか送受信できないような場合も
考慮に入れてやらなければならない。
.TP 
6.
処理するデータ量が小さいことがはっきりとわかっている場合を除いて、 一度に 1 バイトずつ読み書きするようなことはしてはならない。
バッファーの許すかぎりのデータをまとめて読み書きしないと、 非常に効率が悪い。下記の例ではバッファーは 1024 バイトにしているが、
このサイズを大きくするのは簡単だろう。
.TP 
7.
.\" Nonetheless, you should still cope with these errors for completeness.
Calls to \fBread\fP(2), \fBrecv\fP(2), \fBwrite\fP(2), \fBsend\fP(2), and \fBselect\fP()
can fail with the error \fBEINTR\fP, and calls to \fBread\fP(2), \fBrecv\fP(2)
\fBwrite\fP(2), and \fBsend\fP(2)  can fail with \fIerrno\fP set to \fBEAGAIN\fP
(\fBEWOULDBLOCK\fP).  These results must be properly managed (not done properly
above).  If your program is not going to receive any signals, then it is
unlikely you will get \fBEINTR\fP.  If your program does not set nonblocking
I/O, you will not get \fBEAGAIN\fP.
.TP 
8.
決して、引数に長さ 0 のバッファーを指定して \fBread\fP(2), \fBrecv\fP(2), \fBwrite\fP(2), \fBsend\fP(2)
を呼び出してはならない。
.TP 
9.
\fBread\fP(2), \fBrecv\fP(2), \fBwrite\fP(2), \fBsend\fP(2)  が \fB7.\fP に示した以外のエラーで失敗した場合や、
入力系の関数の一つがファイル末尾を表す 0 を返した場合は、 そのファイルディスクリプターをもう一度 select に渡しては\fIならない\fP。
下記の例では、そのファイルディスクリプターをただちにクローズし、 そこには \-1 をセットして、 それが集合に含まれ続けるのを許さないようにしている。
.TP 
10.
タイムアウトの値は \fBselect\fP()  を呼ぶたびに初期化すべきである。 OS によっては timeout
構造体が変更される場合があるからである。 但し、 \fBpselect\fP()  は自分の timeout 構造体を変更することはない。
.TP 
11.
.\" "I have heard" does not fill me with confidence, and doesn't
.\" belong in a man page, so I've commented this point out.
.\" .TP
.\" 11.
.\" I have heard that the Windows socket layer does not cope with OOB data
.\" properly.
.\" It also does not cope with
.\" .BR select ()
.\" calls when no file descriptors are set at all.
.\" Having no file descriptors set is a useful
.\" way to sleep the process with subsecond precision by using the timeout.
.\" (See further on.)
\fBselect\fP()  はファイルディスクリプター集合を変更するので、 \fBselect\fP()
がループの中で使用されている場合には、呼び出しを行う前に毎回 ディスクリプター集合を初期化し直さなければならない。
.SH 返り値
\fBselect\fP(2)  参照。
.SH 注意
一般的に言って、ソケットをサポートする全てのオペレーティングシステムは \fBselect\fP()  もサポートしている。 \fBselect\fP()
を使うと、プログラマがスレッド、フォーク、IPC、シグナル、メモリー共有、 等々を使ってもっと複雑な方法で解決しようとする多くの問題が、
移植性がありかつ効率的な方法で解決できる。
.PP
\fBpoll\fP(2)  システムコールは \fBselect\fP()  と同じ機能を持っており、 まばらなファイルディスクリプター集合を監視する場合に
いくらか効率がよい。 現在では広く利用可能であるが、以前は \fBselect\fP()  より移植性の面で劣っていた。
.PP
Linux 独自の \fBepoll\fP(7)  API は、多数のファイルディスクリプターを監視する場合に \fBselect\fP(2)  や
\fBpoll\fP(2)  よりも効率的なインターフェースを提供している。
.SH 例
\fBselect\fP()  の本当に便利な点を示す、よい例を紹介する。 以下のリストは、ある TCP ポートから別のポートへ転送を行う TCP
フォワードプログラムである。
.PP
.EX
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

static int forward_port;

#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))

static int
listen_socket(int listen_port)
{
    struct sockaddr_in addr;
    int lfd;
    int yes;

    lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lfd == \-1) {
        perror("socket");
        return \-1;
    }

    yes = 1;
    if (setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR,
            &yes, sizeof(yes)) == \-1) {
        perror("setsockopt");
        close(lfd);
        return \-1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_port = htons(listen_port);
    addr.sin_family = AF_INET;
    if (bind(lfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
        perror("bind");
        close(lfd);
        return \-1;
    }

    printf("accepting connections on port %d\en", listen_port);
    listen(lfd, 10);
    return lfd;
}

static int
connect_socket(int connect_port, char *address)
{
    struct sockaddr_in addr;
    int cfd;

    cfd = socket(AF_INET, SOCK_STREAM, 0);
    if (cfd == \-1) {
        perror("socket");
        return \-1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_port = htons(connect_port);
    addr.sin_family = AF_INET;

    if (!inet_aton(address, (struct in_addr *) &addr.sin_addr.s_addr)) {
        fprintf(stderr, "inet_aton(): bad IP address format\en");
        close(cfd);
        return \-1;
    }

    if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) == \-1) {
        perror("connect()");
        shutdown(cfd, SHUT_RDWR);
        close(cfd);
        return \-1;
    }
    return cfd;
}

#define SHUT_FD1 do {                                \e
                     if (fd1 >= 0) {                 \e
                         shutdown(fd1, SHUT_RDWR);   \e
                         close(fd1);                 \e
                         fd1 = \-1;                   \e
                     }                               \e
                 } while (0)

#define SHUT_FD2 do {                                \e
                     if (fd2 >= 0) {                 \e
                         shutdown(fd2, SHUT_RDWR);   \e
                         close(fd2);                 \e
                         fd2 = \-1;                   \e
                     }                               \e
                 } while (0)

#define BUF_SIZE 1024

int
main(int argc, char *argv[])
{
    int h;
    int fd1 = \-1, fd2 = \-1;
    char buf1[BUF_SIZE], buf2[BUF_SIZE];
    int buf1_avail = 0, buf1_written = 0;
    int buf2_avail = 0, buf2_written = 0;

    if (argc != 4) {
        fprintf(stderr, "Usage\en\etfwd <listen\-port> "
                 "<forward\-to\-port> <forward\-to\-ip\-address>\en");
        exit(EXIT_FAILURE);
    }

    signal(SIGPIPE, SIG_IGN);

    forward_port = atoi(argv[2]);

    h = listen_socket(atoi(argv[1]));
    if (h == \-1)
        exit(EXIT_FAILURE);

    for (;;) {
        int ready, nfds = 0;
        ssize_t nbytes;
        fd_set readfds, writefds, exceptfds;

        FD_ZERO(&readfds);
        FD_ZERO(&writefds);
        FD_ZERO(&exceptfds);
        FD_SET(h, &readfds);
        nfds = max(nfds, h);

        if (fd1 > 0 && buf1_avail < BUF_SIZE)
            FD_SET(fd1, &readfds);
            /* Note: nfds is updated below, when fd1 is added to
               exceptfds. */
        if (fd2 > 0 && buf2_avail < BUF_SIZE)
            FD_SET(fd2, &readfds);

        if (fd1 > 0 && buf2_avail \- buf2_written > 0)
            FD_SET(fd1, &writefds);
        if (fd2 > 0 && buf1_avail \- buf1_written > 0)
            FD_SET(fd2, &writefds);

        if (fd1 > 0) {
            FD_SET(fd1, &exceptfds);
            nfds = max(nfds, fd1);
        }
        if (fd2 > 0) {
            FD_SET(fd2, &exceptfds);
            nfds = max(nfds, fd2);
        }

        ready = select(nfds + 1, &readfds, &writefds, &exceptfds, NULL);

        if (ready == \-1 && errno == EINTR)
            continue;

        if (ready == \-1) {
            perror("select()");
            exit(EXIT_FAILURE);
        }

        if (FD_ISSET(h, &readfds)) {
            socklen_t addrlen;
            struct sockaddr_in client_addr;
            int fd;

            addrlen = sizeof(client_addr);
            memset(&client_addr, 0, addrlen);
            fd = accept(h, (struct sockaddr *) &client_addr, &addrlen);
            if (fd == \-1) {
                perror("accept()");
            } else {
                SHUT_FD1;
                SHUT_FD2;
                buf1_avail = buf1_written = 0;
                buf2_avail = buf2_written = 0;
                fd1 = fd;
                fd2 = connect_socket(forward_port, argv[3]);
                if (fd2 == \-1)
                    SHUT_FD1;
                else
                    printf("connect from %s\en",
                            inet_ntoa(client_addr.sin_addr));

                /* Skip any events on the old, closed file
                   descriptors. */

                continue;
            }
        }

        /* NB: read OOB data before normal reads */

        if (fd1 > 0 && FD_ISSET(fd1, &exceptfds)) {
            char c;

            nbytes = recv(fd1, &c, 1, MSG_OOB);
            if (nbytes < 1)
                SHUT_FD1;
            else
                send(fd2, &c, 1, MSG_OOB);
        }
        if (fd2 > 0 && FD_ISSET(fd2, &exceptfds)) {
            char c;

            nbytes = recv(fd2, &c, 1, MSG_OOB);
            if (nbytes < 1)
                SHUT_FD2;
            else
                send(fd1, &c, 1, MSG_OOB);
        }
        if (fd1 > 0 && FD_ISSET(fd1, &readfds)) {
            nbytes = read(fd1, buf1 + buf1_avail,
                      BUF_SIZE \- buf1_avail);
            if (nbytes < 1)
                SHUT_FD1;
            else
                buf1_avail += nbytes;
        }
        if (fd2 > 0 && FD_ISSET(fd2, &readfds)) {
            nbytes = read(fd2, buf2 + buf2_avail,
                      BUF_SIZE \- buf2_avail);
            if (nbytes < 1)
                SHUT_FD2;
            else
                buf2_avail += nbytes;
        }
        if (fd1 > 0 && FD_ISSET(fd1, &writefds) && buf2_avail > 0) {
            nbytes = write(fd1, buf2 + buf2_written,
                       buf2_avail \- buf2_written);
            if (nbytes < 1)
                SHUT_FD1;
            else
                buf2_written += nbytes;
        }
        if (fd2 > 0 && FD_ISSET(fd2, &writefds) && buf1_avail > 0) {
            nbytes = write(fd2, buf1 + buf1_written,
                       buf1_avail \- buf1_written);
            if (nbytes < 1)
                SHUT_FD2;
            else
                buf1_written += nbytes;
        }

        /* Check if write data has caught read data */

        if (buf1_written == buf1_avail)
            buf1_written = buf1_avail = 0;
        if (buf2_written == buf2_avail)
            buf2_written = buf2_avail = 0;

        /* One side has closed the connection, keep
           writing to the other side until empty */

        if (fd1 < 0 && buf1_avail \- buf1_written == 0)
            SHUT_FD2;
        if (fd2 < 0 && buf2_avail \- buf2_written == 0)
            SHUT_FD1;
    }
    exit(EXIT_SUCCESS);
}
.EE
.PP
上記のプログラムは、ほとんどの種類の TCP 接続をフォワードする。 \fBtelnet\fP サーバによって中継される OOB シグナルデータも扱える。
このプログラムは、データフローを双方向に同時に送るという、 ややこしい問題も処理できる。 \fBfork\fP(2)
コールを使って、各ストリームごとに専用のスレッドを用いるほうが効率的だ、 という人もいるかもしれない。しかし、これは考えているよりずっとややこしい。
あるいは、 \fBfcntl\fP(2)  を使って非ブロック I/O をセットすれば良い、というアイデアもあるだろう。
これにも実際には問題があり、タイムアウトが非効率的に起こってしまう。
.PP
このプログラムは一度にひとつ以上の同時接続を扱うことはできないが、 その様に拡張するのは簡単で、バッファーのリンクリストを (接続ごとにひとつずつ)
使えばよい。 現時点のものでは、新しい接続がくると古い接続は落ちてしまう。
.SH 関連項目
.\" .SH AUTHORS
.\" This man page was written by Paul Sheer.
\fBaccept\fP(2), \fBconnect\fP(2), \fBpoll\fP(2), \fBread\fP(2), \fBrecv\fP(2),
\fBselect\fP(2), \fBsend\fP(2), \fBsigprocmask\fP(2), \fBwrite\fP(2), \fBepoll\fP(7)
.SH この文書について
この man ページは Linux \fIman\-pages\fP プロジェクトのリリース 5.10 の一部である。プロジェクトの説明とバグ報告に関する情報は
\%https://www.kernel.org/doc/man\-pages/ に書かれている。