select_tutのヘルプ・マニュアル
日本語 英語
select_tut --help
man select_tut
SELECT_TUT(2) Linux Programmer’s Manual SELECT_TUT(2)
名前
select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - 同期 I/O の多重化
書式
/* POSIX.1-2001 に従う場合 */
#include
/* 以前の規格に従う場合 */
#include
#include
#include
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *utimeout);
void FD_CLR(int fd, fd_set *set);
int FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
#include
int pselect(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timespec *ntimeout,
const sigset_t *sigmask);
glibc 向けの機能検査マクロの要件 (feature_test_macros(7) 参照):
pselect(): _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600
説明
select() (や pselect()) を使うと、効率的に複数のファイルディスクリプタ
を監視し、そのファイルディスクリプタのいずれかが「ready (準備ができ た)
」 状態、つまり I/O (入出力) が可能になっているかや、ファイルディスクリ
プタのいずれかが「例外状態 (exceptional condition)」が発生したか、を 調
べることができる。
こ の 関 数 の 主 要な引き数は、3種類のファイルディスクリプタの「集合」
readfds, writefds, exceptfds である。各々の集合は fd_set として宣言され
、その内容は FD_CLR(), FD_ISSET(), FD_SET(), FD_ZERO() といったマクロに
よって操作できる。新しく宣言された集合は、まず最初に FD_ZERO() を使って
ク リアすべきである。 select() はこれらの集合の内容を、以降に述べる規則
に従って修正する。 select() を呼んだ後、ファイルディスクリプタがまだ 集
合 に存在しているかどうかは、 FD_ISSET() マクロによって調べることができ
る。 FD_ISSET() は指定されたディスクリプタが集合に存在していれば 0 以外
の値を返し、存在しなければ 0 を返す。 FD_CLR() は集合からのファイルディ
スクリプタの削除を行う。
引き数
readfds
この集合に含まれるいずれかのファイルディスクリプタで、データの読
み 込 みが可能になったかどうかを監視する。 select() から戻る時に
、readfds のうち、直ちに読み込み可能なファイルディスクリプタ以外
は集合から削除される。
writefds
この集合に含まれるいずれかのファイルディスクリプタで、データを書
き込むスペースがあるかどうかを監視する。 select() から戻る 時 に
、writefds のうち、直ちに書き込み可能なファイルディスクリプタ以
外は集合から削除される。
exceptfds
この集合に含まれるいずれかのファイルディスクリプタで、「例外状態
(exceptional condition)」が発生したかどうかを監視する。実際の動
作では、普通に起こり得る例外状態は一つだけであり、それは TCP ソ
ケ ットで 帯域外 (out-of-band; OOB) データが読み込み可能な場合で
ある。 OOB データの詳細については、 recv(2), send(2), tcp(7) を
参照のこと。 (これ以外では、まれなことだが、パケットモードの擬似
端末 (pseudo-terminals) で select() が例外状態を示すことが あ る
。) select() が返る時に、exceptfds のうち、例外状態が発生したデ
ィスクリプタ以外は集合から削除される。
nfds 全ての集合に含まれるファイルディスクリプタのうち、値が最大のもの
に 1 を足した整数である。すなわち、ファイルディスクリプタを各集
合に加える作業の途中で、全てのファイルディスクリプタを見て最大値
を 求め、それに 1 を加えて nfds として渡さないといけない、という
ことだ。
utimeout
(何も起こらなかった場合に) select() が戻る前に待つ最大時間である
。この値に NULL を渡すと、 select() はファイルディスクリプタのい
ずれかが ready (準備ができた) 状態になるまで待ち続けてずっと停止
す る。 utimeout は 0 秒にすることもでき、この場合 select() は直
ちに返り、呼び出し時点のファイルディスクリプタの状態に関する情報
が返される。構造体 struct timeval は次のように定義されている:
struct timeval {
time_t tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
ntimeout
pselect() の この引き数は utimeout と同じ意味を持つが、 struct
timespec は次に示すようにナノ秒の精度を持つ。
struct timespec {
long tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
sigmask
この引き数は、呼び出し側が pselect() 内部で停止している間に、 カ
ーネルが通知を許可すべきシグナル集合 (すなわち、呼び出したスレッ
ドのシグナルマスクから削除すべきシグナル 集 合) を 保 持 す る
(sigaddset(3) と sigprocmask(2) を参照)。この引き数は NULL にす
ることもでき、その場合はこの関数へ入るとき・出るときにシグナルマ
ス クを変更しない。この場合、 pselect() は select() と全く同じ動
作となる。
シグナルとデータイベントを組み合わせる
ファイルディスクリプタが I/O 可能な状態になるのと同時にシグナルも待ちた
い場合には、 pselect() が便利である。シグナルを受信するプログラムは、通
常は、シグナルハンドラをグローバルなフラグを立てるためだけに使う。こ の
グ ローバルなフラグは、そのイベントをプログラムのメインループで処理しな
ければならないことを示す。シグナルを受けると select() (や pselect()) は
errno に EINTR をセットして戻ることになる。シグナルがプログラムのメイン
ループで処理されるためにはこの動作が不可欠で、これがないと select() は
永 遠に停止し続けることになる。さて、メインループのどこかにこのグローバ
ルフラグをチェックする条件文があるとしよう。ここで少し考えてみないと い
け ない。「シグナルが条件文の後、しかし select() コールの前に到着したら
どうなるのか?」答えは「その select() は、たとえ解決待ちのイベントが あ
ったとしても、永遠に停止する」である。この競合状態は pselect() コールに
よって解決できる。このコールを使うと、 pselect() で受信したいシグナルの
集 合だけをシグナルマスクに設定することができる。例えば、問題となってい
るイベントが子プロセスの終了の場合を考えよう。メインループが始まる前 に
、 SIGCHLD を sigprocmask(2) でブロックする。 pselect() コールでは
SIGCHLD を、もともとのシグナルマスクを使って有効にするのだ。このプロ グ
ラムは次のようになる。
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 */
}
}
実例
実 際のところ select() の大事な点は何なのか?ディスクリプタは好きなとき
に読み書きできるんじゃないの? select() の重要なところは、複数のディ ス
ク リプタを同時に監視でき、なんの動きもなければプロセスを適切にスリープ
状態に移行するところにあるのだ。 Unix プログラマは、複数のファイルデ ィ
ス クリプタの入出力を同時に扱わねばならず、しかもデータの流れは間欠的で
ある、という状況によく出会う。単に read(2) や write(2) コールのシーケン
ス を作るだけでは、それらのコールのどれかがファイルディスクリプタからの
データを待ってブロックしており、別のファイルディスクリプタには I/O が可
能 なのに使えない、ということになってしまうだろう。 select() を使うとこ
の状況に効果的に対処できる。
SELECT の掟
select() を使おうとした多くの人は、理解しにくい挙動に出くわし、結果的に
で きたものは移植性がないか、よくてもギリギリのものになってしまう。例え
ば、上記のプログラムは、集合に含まれるファイルディスクリプタを 非 停 止
(non-blocking) モードにしなくても、どこにもブロックが生じないよう注意し
て書かれている。微妙な間違いによって、 select() を使う利点は簡単に失 わ
れ てしまう。そこで、 select() コールを使うときに注意すべき重要事項を列
挙しておくことにする。
1. select() を使うときは、タイムアウトは設定すべきでない。処理するデー
タ が無いときには、あなたのプログラムには何もすることは無いはずであ
る。タイムアウトに依存したコードは通常移植性がなく、デバッグも難 し
くなる。
2. 上述したように、効率的なプログラムを書くには nfds の値を適切に計算
して与えなければならない。
3. select() コールの終了後に結果をチェックして、適切に対応するつもりの
な いファイルディスクリプタは、どの集合にも加えてはならない。次のル
ールも参照。
4. select() から返った後には、全ての集合の全てのファイルディスクリプタ
について読み書き可能な状態になっているかをチェックすべきである。
5. read(2), recv(2), write(2), send(2) といった関数は、こちらが要求し
た全データを読み書きする必要はない。もし全データを読み書きするな ら
、 それはトラフィックの負荷が小さく、ストリームが速い場合だろう。こ
の条件は常に満たされるとは限らない。これらの関数が頑張っても 1 バイ
トしか送受信できないような場合も考慮に入れてやらなければならない。
6. 処理するデータ量が小さいことがはっきりとわかっている場合を除いて、
一度に 1 バイトずつ読み書きするようなことはしてはならない。バッファ
の 許すかぎりのデータをまとめて読み書きしないと、非常に効率が悪い。
下記の例ではバッファは 1024 バイトにしているが、このサイズを大き く
するのは簡単だろう。
7. read(2), recv(2), write(2), send(2) などの関数や select() コールは
、 errno を EINTR や EAGAIN (EWOULDBLOCK) にして -1 を返すこと が
あ る。このような結果に対して適切に対応してやらなければならない (上
記の例ではしていない)。書いているプログラムがシグナルを受ける予定が
なければ、 EINTR が返されることはあまり考えられない。書いているプロ
グラムで非ブロック I/O をセットしていない場合は、 EAGAIN が返される
ことはないだろう。
8. 決 し て 、 引 き数に長さ 0 のバッファを指定して read(2), recv(2),
write(2), send(2) を呼び出してはならない。
9. read(2), recv(2), write(2), send(2) が 7. に示した以外のエラーで 失
敗した場合や、入力系の関数の一つがファイル末尾を表す 0 を返した場合
は、そのディスクリプタをもう一度 select に渡してはならない。下記 の
例 では、そのディスクリプタをただちにクローズし、そこには -1 をセッ
トして、それが集合に含まれ続けるのを許さないようにしている。
10. タイムアウトの値は select() を呼ぶたびに初期化すべきである。 OS に
よ っ て は timeout 構造体が変更される場合があるからである。但し、
pselect() は自分の timeout 構造体を変更することはない。
11. select() はファイルディスクリプタ集合を変更するので、 select() がル
ー プの中で使用されている場合には、呼び出しを行う前に毎回ディスクリ
プタ集合を初期化し直さなければならない。
usleep エミュレーション
usleep(3) 関数を持たないシステムでは、有限のタイムアウトを指定し、フ ァ
イ ルディスクリプタを全くセットせずに select() を呼び出すことで、これを
代用できる。以下のようにする。
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 200000; /* 0.2 seconds */
select(0, NULL, NULL, NULL, &tv);
但し、これが動くと保証されているのは Unix システムに限られる。
返り値
成功すると、 select() はファイルディスクリプタ集合に残っているファイ ル
ディスクリプタの総数を返す。
select() がタイムアウトすると、返り値は 0 になる。その時、ファイルディ
スクリプタ集合はすべて空である (しかしそうならないシステムもある)。
返り値が -1 の場合はエラーを意味し、 errno が適切にセットされる。エラー
が 起こった場合、返された集合の内容や構造体 struct timeout の内容は未定
義となっており、使用すべきではない。しかし pselect() は決して ntimeout
を変更しない。
注意
一 般的に言って、ソケットをサポートする全てのオペレーティングシステムは
select() もサポートしている。 select() を使うと、プログラマがスレッド、
フォーク、IPC、シグナル、メモリ共有、等々を使ってもっと複雑な方法で解決
しようとする多くの問題が、移植性がありかつ効率的な方法で解決できる。
poll(2) システムコールは select() と同じ機能を持っており、まばらなフ ァ
イ ルディスクリプタ集合を監視する場合にいくらか効率がよい。現在では広く
利用可能であるが、以前は select() より移植性の面で劣っていた。
Linux 独自の epoll(7) API は、多数のファイルディスクリプタを監視する 場
合に select(2) や poll(2) よりも効率的なインタフェースを提供している。
例
select() の本当に便利な点を示す、よい例を紹介する。以下のリストは、ある
TCP ポートから別のポートへ転送を行う TCP フォワードプログラムである。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static int forward_port;
#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))
static int
listen_socket(int listen_port)
{
struct sockaddr_in a;
int s;
int yes;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
return -1;
}
yes = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
(char *) &yes, sizeof(yes)) == -1) {
perror("setsockopt");
close(s);
return -1;
}
memset(&a, 0, sizeof(a));
a.sin_port = htons(listen_port);
a.sin_family = AF_INET;
if (bind(s, (struct sockaddr *) &a, sizeof(a)) == -1) {
perror("bind");
close(s);
return -1;
}
printf("accepting connections on port %d\n", listen_port);
listen(s, 10);
return s;
}
static int
connect_socket(int connect_port, char *address)
{
struct sockaddr_in a;
int s;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
close(s);
return -1;
}
memset(&a, 0, sizeof(a));
a.sin_port = htons(connect_port);
a.sin_family = AF_INET;
if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
perror("bad IP address format");
close(s);
return -1;
}
if (connect(s, (struct sockaddr *) &a, sizeof(a)) == -1) {
perror("connect()");
shutdown(s, SHUT_RDWR);
close(s);
return -1;
}
return s;
}
#define SHUT_FD1 do { \
if (fd1 >= 0) { \
shutdown(fd1, SHUT_RDWR); \
close(fd1); \
fd1 = -1; \
} \
} while (0)
#define SHUT_FD2 do { \
if (fd2 >= 0) { \
shutdown(fd2, SHUT_RDWR); \
close(fd2); \
fd2 = -1; \
} \
} 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, buf1_written;
int buf2_avail, buf2_written;
if (argc != 4) {
fprintf(stderr, "Usage\n\tfwd "
" \n");
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 r, nfds = 0;
fd_set rd, wr, er;
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&er);
FD_SET(h, &rd);
nfds = max(nfds, h);
if (fd1 > 0 && buf1_avail < BUF_SIZE) {
FD_SET(fd1, &rd);
nfds = max(nfds, fd1);
}
if (fd2 > 0 && buf2_avail < BUF_SIZE) {
FD_SET(fd2, &rd);
nfds = max(nfds, fd2);
}
if (fd1 > 0 && buf2_avail - buf2_written > 0) {
FD_SET(fd1, &wr);
nfds = max(nfds, fd1);
}
if (fd2 > 0 && buf1_avail - buf1_written > 0) {
FD_SET(fd2, &wr);
nfds = max(nfds, fd2);
}
if (fd1 > 0) {
FD_SET(fd1, &er);
nfds = max(nfds, fd1);
}
if (fd2 > 0) {
FD_SET(fd2, &er);
nfds = max(nfds, fd2);
}
r = select(nfds + 1, &rd, &wr, &er, NULL);
if (r == -1 && errno == EINTR)
continue;
if (r == -1) {
perror("select()");
exit(EXIT_FAILURE);
}
if (FD_ISSET(h, &rd)) {
unsigned int l;
struct sockaddr_in client_address;
memset(&client_address, 0, l = sizeof(client_address));
r = accept(h, (struct sockaddr *) &client_address, &l);
if (r == -1) {
perror("accept()");
} else {
SHUT_FD1;
SHUT_FD2;
buf1_avail = buf1_written = 0;
buf2_avail = buf2_written = 0;
fd1 = r;
fd2 = connect_socket(forward_port, argv[3]);
if (fd2 == -1)
SHUT_FD1;
else
printf("connect from %s\n",
inet_ntoa(client_address.sin_addr));
}
}
/* NB: read oob data before normal reads */
if (fd1 > 0)
if (FD_ISSET(fd1, &er)) {
char c;
r = recv(fd1, &c, 1, MSG_OOB);
if (r < 1)
SHUT_FD1;
else
send(fd2, &c, 1, MSG_OOB);
}
if (fd2 > 0)
if (FD_ISSET(fd2, &er)) {
char c;
r = recv(fd2, &c, 1, MSG_OOB);
if (r < 1)
SHUT_FD1;
else
send(fd1, &c, 1, MSG_OOB);
}
if (fd1 > 0)
if (FD_ISSET(fd1, &rd)) {
r = read(fd1, buf1 + buf1_avail,
BUF_SIZE - buf1_avail);
if (r < 1)
SHUT_FD1;
else
buf1_avail += r;
}
if (fd2 > 0)
if (FD_ISSET(fd2, &rd)) {
r = read(fd2, buf2 + buf2_avail,
BUF_SIZE - buf2_avail);
if (r < 1)
SHUT_FD2;
else
buf2_avail += r;
}
if (fd1 > 0)
if (FD_ISSET(fd1, &wr)) {
r = write(fd1, buf2 + buf2_written,
buf2_avail - buf2_written);
if (r < 1)
SHUT_FD1;
else
buf2_written += r;
}
if (fd2 > 0)
if (FD_ISSET(fd2, &wr)) {
r = write(fd2, buf1 + buf1_written,
buf1_avail - buf1_written);
if (r < 1)
SHUT_FD2;
else
buf1_written += r;
}
/* 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);
}
上記のプログラムは、ほとんどの種類の TCP 接続をフォワードする。 telnet
サーバによって中継される OOB シグナルデータも扱える。このプログラムは、
データフローを双方向に同時に送るという、ややこしい問題も処理で き る 。
fork(2) コールを使って、各ストリームごとに専用のスレッドを用いるほうが
効率的だ、という人もいるかもしれない。しかし、これは考えているよりず っ
とややこしい。あるいは、 fcntl(2) を使って非ブロック I/O をセットすれば
良い、というアイデアもあるだろう。これにも実際には問題があり、タイム ア
ウトが非効率的に起こってしまう。
こ のプログラムは一度にひとつ以上の同時接続を扱うことはできないが、その
様に拡張するのは簡単で、バッファのリンクリストを (接続ごとにひとつずつ)
使 えばよい。現時点のものでは、新しい接続がくると古い接続は落ちてしまう
。
関連項目
accept(2), connect(2), ioctl(2), poll(2), read(2), recv(2), select(2),
send(2), sigprocmask(2), write(2), sigaddset(3), sigdelset(3), sigemp-
tyset(3), sigfillset(3), sigismember(3), epoll(7)
Linux 2009-01-26 SELECT_TUT(2)
SELECT_TUT(2) Linux Programmer’s Manual SELECT_TUT(2)
NAME
select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O
multiplexing
SYNOPSIS
/* According to POSIX.1-2001 */
#include
/* According to earlier standards */
#include
#include
#include
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *utimeout);
void FD_CLR(int fd, fd_set *set);
int FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
#include
int pselect(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timespec *ntimeout,
const sigset_t *sigmask);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
pselect(): _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600
DESCRIPTION
select() (or pselect()) is used to efficiently monitor multiple file
descriptors, to see if any of them is, or becomes, "ready"; that is, to
see whether I/O becomes possible, or an "exceptional condition" has
occurred on any of the descriptors.
Its principal arguments are three "sets" of file descriptors: readfds,
writefds, and exceptfds. Each set is declared as type fd_set, and its
contents can be manipulated with the macros FD_CLR(), FD_ISSET(),
FD_SET(), and FD_ZERO(). A newly declared set should first be cleared
using FD_ZERO(). select() modifies the contents of the sets according
to the rules described below; after calling select() you can test if a
file descriptor is still present in a set with the FD_ISSET() macro.
FD_ISSET() returns non-zero if a specified file descriptor is present
in a set and zero if it is not. FD_CLR() removes a file descriptor
from a set.
Arguments
readfds
This set is watched to see if data is available for reading from
any of its file descriptors. After select() has returned,
readfds will be cleared of all file descriptors except for those
that are immediately available for reading.
writefds
This set is watched to see if there is space to write data to
any of its file descriptors. After select() has returned,
writefds will be cleared of all file descriptors except for
those that are immediately available for writing.
exceptfds
This set is watched for "exceptional conditions". In practice,
only one such exceptional condition is common: the availability
of out-of-band (OOB) data for reading from a TCP socket. See
recv(2), send(2), and tcp(7) for more details about OOB data.
(One other less common case where select(2) indicates an excep-
tional condition occurs with pseudo-terminals in packet mode;
see tty_ioctl(4).) After select() has returned, exceptfds will
be cleared of all file descriptors except for those for which an
exceptional condition has occurred.
nfds This is an integer one more than the maximum of any file
descriptor in any of the sets. In other words, while adding
file descriptors each of the sets, you must calculate the maxi-
mum integer value of all of them, then increment this value by
one, and then pass this as nfds.
utimeout
This is the longest time select() may wait before returning,
even if nothing interesting happened. If this value is passed
as NULL, then select() blocks indefinitely waiting for a file
descriptor to become ready. utimeout can be set to zero sec-
onds, which causes select() to return immediately, with informa-
tion about the readiness of file descriptors at the time of the
call. The structure struct timeval is defined as:
struct timeval {
time_t tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
ntimeout
This argument for pselect() has the same meaning as utimeout,
but struct timespec has nanosecond precision as follows:
struct timespec {
long tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
sigmask
This argument holds a set of signals that the kernel should
unblock (i.e., remove from the signal mask of the calling
thread), while the caller is blocked inside the pselect() call
(see sigaddset(3) and sigprocmask(2)). It may be NULL, in which
case the call does not modify the signal mask on entry and exit
to the function. In this case, pselect() will then behave just
like select().
Combining Signal and Data Events
pselect() is useful if you are waiting for a signal as well as for file
descriptor(s) to become ready for I/O. Programs that receive signals
normally use the signal handler only to raise a global flag. The
global flag will indicate that the event must be processed in the main
loop of the program. A signal will cause the select() (or pselect())
call to return with errno set to EINTR. This behavior is essential so
that signals can be processed in the main loop of the program, other-
wise select() would block indefinitely. Now, somewhere in the main
loop will be a conditional to check the global flag. So we must ask:
what if a signal arrives after the conditional, but before the select()
call? The answer is that select() would block indefinitely, even
though an event is actually pending. This race condition is solved by
the pselect() call. This call can be used to set the siognal mask to a
set of signals that are only to be received within the pselect() call.
For instance, let us say that the event in question was the exit of a
child process. Before the start of the main loop, we would block
SIGCHLD using sigprocmask(2). Our pselect() call would enable SIGCHLD
by using an empty signal mask. Our program would look like:
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 */
}
}
Practical
So what is the point of select()? Can’t I just read and write to my
descriptors whenever I want? The point of select() is that it watches
multiple descriptors at the same time and properly puts the process to
sleep if there is no activity. Unix programmers often find themselves
in a position where they have to handle I/O from more than one file
descriptor where the data flow may be intermittent. If you were to
merely create a sequence of read(2) and write(2) calls, you would find
that one of your calls may block waiting for data from/to a file
descriptor, while another file descriptor is unused though ready for
I/O. select() efficiently copes with this situation.
Select Law
Many people who try to use select() come across behavior that is diffi-
cult to understand and produces non-portable or borderline results.
For instance, the above program is carefully written not to block at
any point, even though it does not set its file descriptors to non-
blocking mode. It is easy to introduce subtle errors that will remove
the advantage of using select(), so here is a list of essentials to
watch for when using select().
1. You should always try to use select() without a timeout. Your pro-
gram should have nothing to do if there is no data available. Code
that depends on timeouts is not usually portable and is difficult
to debug.
2. The value nfds must be properly calculated for efficiency as
explained above.
3. No file descriptor must be added to any set if you do not intend to
check its result after the select() call, and respond appropri-
ately. See next rule.
4. After select() returns, all file descriptors in all sets should be
checked to see if they are ready.
5. The functions read(2), recv(2), write(2), and send(2) do not neces-
sarily read/write the full amount of data that you have requested.
If they do read/write the full amount, it’s because you have a low
traffic load and a fast stream. This is not always going to be the
case. You should cope with the case of your functions only manag-
ing to send or receive a single byte.
6. Never read/write only in single bytes at a time unless you are
really sure that you have a small amount of data to process. It is
extremely inefficient not to read/write as much data as you can
buffer each time. The buffers in the example below are 1024 bytes
although they could easily be made larger.
7. The functions read(2), recv(2), write(2), and send(2) as well as
the select() call can return -1 with errno set to EINTR, or with
errno set to EAGAIN (EWOULDBLOCK). 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 EINTR. If
your program does not set non-blocking I/O, you will not get
EAGAIN.
8. Never call read(2), recv(2), write(2), or send(2) with a buffer
length of zero.
9. If the functions read(2), recv(2), write(2), and send(2) fail with
errors other than those listed in 7., or one of the input functions
returns 0, indicating end of file, then you should not pass that
descriptor to select() again. In the example below, I close the
descriptor immediately, and then set it to -1 to prevent it being
included in a set.
10. The timeout value must be initialized with each new call to
select(), since some operating systems modify the structure. pse-
lect() however does not modify its timeout structure.
11. Since select() modifies its file descriptor sets, if the call is
being used in a loop, then the sets must be re-initialized before
each call.
Usleep Emulation
On systems that do not have a usleep(3) function, you can call select()
with a finite timeout and no file descriptors as follows:
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 200000; /* 0.2 seconds */
select(0, NULL, NULL, NULL, &tv);
This is only guaranteed to work on Unix systems, however.
RETURN VALUE
On success, select() returns the total number of file descriptors still
present in the file descriptor sets.
If select() timed out, then the return value will be zero. The file
descriptors set should be all empty (but may not be on some systems).
A return value of -1 indicates an error, with errno being set appropri-
ately. In the case of an error, the contents of the returned sets and
the struct timeout contents are undefined and should not be used. pse-
lect() however never modifies ntimeout.
NOTES
Generally speaking, all operating systems that support sockets also
support select(). select() can be used to solve many problems in a
portable and efficient way that naive programmers try to solve in a
more complicated manner using threads, forking, IPCs, signals, memory
sharing, and so on.
The poll(2) system call has the same functionality as select(), and is
somewhat more efficient when monitoring sparse file descriptor sets.
It is nowadays widely available, but historically was less portable
than select().
The Linux-specific epoll(7) API provides an interface that is more
efficient than select(2) and poll(2) when monitoring large numbers of
file descriptors.
EXAMPLE
Here is an example that better demonstrates the true utility of
select(). The listing below is a TCP forwarding program that forwards
from one TCP port to another.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static int forward_port;
#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))
static int
listen_socket(int listen_port)
{
struct sockaddr_in a;
int s;
int yes;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
return -1;
}
yes = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
(char *) &yes, sizeof(yes)) == -1) {
perror("setsockopt");
close(s);
return -1;
}
memset(&a, 0, sizeof(a));
a.sin_port = htons(listen_port);
a.sin_family = AF_INET;
if (bind(s, (struct sockaddr *) &a, sizeof(a)) == -1) {
perror("bind");
close(s);
return -1;
}
printf("accepting connections on port %d\n", listen_port);
listen(s, 10);
return s;
}
static int
connect_socket(int connect_port, char *address)
{
struct sockaddr_in a;
int s;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
close(s);
return -1;
}
memset(&a, 0, sizeof(a));
a.sin_port = htons(connect_port);
a.sin_family = AF_INET;
if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
perror("bad IP address format");
close(s);
return -1;
}
if (connect(s, (struct sockaddr *) &a, sizeof(a)) == -1) {
perror("connect()");
shutdown(s, SHUT_RDWR);
close(s);
return -1;
}
return s;
}
#define SHUT_FD1 do { \
if (fd1 >= 0) { \
shutdown(fd1, SHUT_RDWR); \
close(fd1); \
fd1 = -1; \
} \
} while (0)
#define SHUT_FD2 do { \
if (fd2 >= 0) { \
shutdown(fd2, SHUT_RDWR); \
close(fd2); \
fd2 = -1; \
} \
} 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, buf1_written;
int buf2_avail, buf2_written;
if (argc != 4) {
fprintf(stderr, "Usage\n\tfwd "
" \n");
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 r, nfds = 0;
fd_set rd, wr, er;
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&er);
FD_SET(h, &rd);
nfds = max(nfds, h);
if (fd1 > 0 && buf1_avail < BUF_SIZE) {
FD_SET(fd1, &rd);
nfds = max(nfds, fd1);
}
if (fd2 > 0 && buf2_avail < BUF_SIZE) {
FD_SET(fd2, &rd);
nfds = max(nfds, fd2);
}
if (fd1 > 0 && buf2_avail - buf2_written > 0) {
FD_SET(fd1, &wr);
nfds = max(nfds, fd1);
}
if (fd2 > 0 && buf1_avail - buf1_written > 0) {
FD_SET(fd2, &wr);
nfds = max(nfds, fd2);
}
if (fd1 > 0) {
FD_SET(fd1, &er);
nfds = max(nfds, fd1);
}
if (fd2 > 0) {
FD_SET(fd2, &er);
nfds = max(nfds, fd2);
}
r = select(nfds + 1, &rd, &wr, &er, NULL);
if (r == -1 && errno == EINTR)
continue;
if (r == -1) {
perror("select()");
exit(EXIT_FAILURE);
}
if (FD_ISSET(h, &rd)) {
unsigned int l;
struct sockaddr_in client_address;
memset(&client_address, 0, l = sizeof(client_address));
r = accept(h, (struct sockaddr *) &client_address, &l);
if (r == -1) {
perror("accept()");
} else {
SHUT_FD1;
SHUT_FD2;
buf1_avail = buf1_written = 0;
buf2_avail = buf2_written = 0;
fd1 = r;
fd2 = connect_socket(forward_port, argv[3]);
if (fd2 == -1)
SHUT_FD1;
else
printf("connect from %s\n",
inet_ntoa(client_address.sin_addr));
}
}
/* NB: read oob data before normal reads */
if (fd1 > 0)
if (FD_ISSET(fd1, &er)) {
char c;
r = recv(fd1, &c, 1, MSG_OOB);
if (r < 1)
SHUT_FD1;
else
send(fd2, &c, 1, MSG_OOB);
}
if (fd2 > 0)
if (FD_ISSET(fd2, &er)) {
char c;
r = recv(fd2, &c, 1, MSG_OOB);
if (r < 1)
SHUT_FD1;
else
send(fd1, &c, 1, MSG_OOB);
}
if (fd1 > 0)
if (FD_ISSET(fd1, &rd)) {
r = read(fd1, buf1 + buf1_avail,
BUF_SIZE - buf1_avail);
if (r < 1)
SHUT_FD1;
else
buf1_avail += r;
}
if (fd2 > 0)
if (FD_ISSET(fd2, &rd)) {
r = read(fd2, buf2 + buf2_avail,
BUF_SIZE - buf2_avail);
if (r < 1)
SHUT_FD2;
else
buf2_avail += r;
}
if (fd1 > 0)
if (FD_ISSET(fd1, &wr)) {
r = write(fd1, buf2 + buf2_written,
buf2_avail - buf2_written);
if (r < 1)
SHUT_FD1;
else
buf2_written += r;
}
if (fd2 > 0)
if (FD_ISSET(fd2, &wr)) {
r = write(fd2, buf1 + buf1_written,
buf1_avail - buf1_written);
if (r < 1)
SHUT_FD2;
else
buf1_written += r;
}
/* 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);
}
The above program properly forwards most kinds of TCP connections
including OOB signal data transmitted by telnet servers. It handles
the tricky problem of having data flow in both directions simultane-
ously. You might think it more efficient to use a fork(2) call and
devote a thread to each stream. This becomes more tricky than you
might suspect. Another idea is to set non-blocking I/O using fcntl(2).
This also has its problems because you end up using inefficient time-
outs.
The program does not handle more than one simultaneous connection at a
time, although it could easily be extended to do this with a linked
list of buffers — one for each connection. At the moment, new connec-
tions cause the current connection to be dropped.
SEE ALSO
accept(2), connect(2), ioctl(2), poll(2), read(2), recv(2), select(2),
send(2), sigprocmask(2), write(2), sigaddset(3), sigdelset(3), sigemp-
tyset(3), sigfillset(3), sigismember(3), epoll(7)
COLOPHON
This page is part of release 3.22 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at http://www.kernel.org/doc/man-pages/.
Linux 2009-01-26 SELECT_TUT(2)