Linux socket Select(2) (翻译 man 2)

 

SELECT(2)                     Linux Programmer's Manual                     SELECT(2)

NAME

       select,  pselect,  FD_CLR,  FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multi-plexing.同步的IO复用

SYNOPSIS

       /* According to POSIX.1-2001 */
       #include <sys/select.h>

       /* According to earlier standards */
       #include <sys/time.h>
       #include <sys/types.h>
       #include <unistd.h>

       int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);

       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 <sys/select.h>

       int pselect(int nfds, fd_set *readfds, fd_set *writefds,
                   fd_set *exceptfds, const struct timespec *timeout,
                   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() and pselect() allow a program to monitor multiple file descriptors,
       waiting until one or more of the file descriptors become "ready" for some
       class of I/O operation (e.g., input possible).  A file descriptor is
       considered ready if it is possible to perform the corresponding I/O operation
       (e.g., read(2)) without blocking.
 select() 和 pselect() 允许程序监视多个文件描述符(fd),一直等待直到在一些IO操作中一个或多个fd变为"ready"状态(如可以输入)当fd能够进行对应的IO操作的时候就认为是非阻塞的(如read).
       The operation of select() and pselect() is identical, with three differences:

       (i)    select() uses a timeout that is a struct timeval (with seconds and
              microseconds), while pselect() uses a struct timespec (with seconds and
              nanoseconds).

       (ii)   select() may update the timeout argument to indicate how much time was
              left.  pselect() does not change this argument.

       (iii)  select() has no sigmask argument, and behaves as pselect() called with
              NULL sigmask.
select() 和 pselect() 是完全一致的,除了以下3处不同:
(i) select() 使用 struct timeval 这个结构体(使用秒和毫秒)来表示超时时间,而 pselect() 使用 struct timespec (使用秒和纳秒)来表示超时.
(ii) select() 可以更新timeout 参数来表示还有多少时间剩余,而 pselect() 不可改变参数.
(iii) select() 没有 sigmask  参数,而 pselect() 被NULL sigmask  调用.
       Three independent sets of file descriptors are watched.  Those listed in
       readfds will be watched to see if characters become available for reading
       (more precisely, to see if a read will not block; in particular, a file
       descriptor is also ready on end-of-file), those in writefds will be watched to
       see if a write will not block, and those in exceptfds will be watched for
       exceptions.  On exit, the sets are modified in place to indicate which file
       descriptors actually changed status.  Each of the three file descriptor sets
       may be specified as NULL if no file descriptors are to be watched for the
       corresponding class of events.
三种独立的fd标志位被监视着.在 readfds 中的标志位将会监视fd是否可读(更重要的是,可以检测读操作是否阻塞;特殊的,fd在EOF也是可读的).在writefds 中的标志位将会监视fd的写操作是否阻塞.在 exceptfds 中的标志位监视发生的意外.
退出的时候,标志位会被改变来标识fd的哪个位置改变了状态.每个fd的标志位可以指定为NULL如果没有fd的对应事件被监视的话.
       Four macros are provided to manipulate the sets.  FD_ZERO() clears a set.
       FD_SET() and FD_CLR() respectively add and remove a given file descriptor from
       a set.  FD_ISSET() tests to see if a file descriptor is part of the set; this
       is useful after select() returns.
提供四个宏来操作这些标志位.FD_ZERO() 清零标志位.FD_SET() 和 FD_CLR() 分别从标志位中增加和去除一个指定的fd;.FD_ISSET() 检测一个fd是否是一个标志位的一部分;这在 select() 返回的时候是很有用的.
       nfds is the highest-numbered file descriptor in any of the three sets, plus 1.
nfds 是3个标志位中的最大值,加1
       timeout is an upper bound on the amount of time elapsed before select()
       returns.  If both fields of the timeval structure are zero, then select()
       returns immediately.  (This is useful for polling.)  If timeout is NULL (no
       timeout), select() can block indefinitely.
timeoutselect() 返回之前的时间上限.如果timeval 的二个成员值都为0, select() 会立即返回(这对polling(l轮询)有用).如果timeout 为NULL(不设置超时),select() 会一直阻塞.

       sigmask is a pointer to a signal mask (see sigprocmask(2)); if it is not NULL,
       then pselect() first replaces the current signal mask by the one pointed to by
       sigmask, then does the "select" function, and then restores the original
       signal mask.
sigmask 是一个指向signal mask 的指针,如果它不为NULL,pselect() 首先更换根据sigmask 指向的signal mask,之后做和select() 一样的事情,最后回复最初的signal mask.
       Other than the difference in the precision of the timeout argument, the
       following pselect() call:

           ready = pselect(nfds, &readfds, &writefds, &exceptfds,
                           timeout, &sigmask);

       is equivalent to atomically executing the following calls:
除了timeout 参数的精确度不同,以上的pselect() 等同于下面的原子操作
           sigset_t origmask;

           sigprocmask(SIG_SETMASK, &sigmask, &origmask);
           ready = select(nfds, &readfds, &writefds, &exceptfds, timeout);
           sigprocmask(SIG_SETMASK, &origmask, NULL);

       The reason that pselect() is needed is that if one wants to wait for either a
       signal or for a file descriptor to become ready, then an atomic test is needed
       to prevent race conditions.  (Suppose the signal handler sets a global flag
       and returns.  Then a test of this global flag followed by a call of select()
       could hang indefinitely if the signal arrived just after the test but just
       before the call.  By contrast, pselect() allows one to first block signals,
       handle the signals that have come in, then call pselect() with the desired
       sigmask, avoiding the race.)
需要 pselect() 的原因是:如果想等待要么来自于信号或者是来自fd变为ready,一个原子操作就被需要来防止竞争.(假设一个信号处理程序设置了一个全局的标志位并返回,接着对这个全局标志位的测试后跟着一个select()
的调用,如果就在测试开始之后信号来临的话那么select()就会无限期的挂起.与之相对的,pselect() 允许先阻塞信号,然后处理进入的信号,之后通过想要的sigmask再调用pselect() 来避免竞争.

The timeout

       The time structures involved are defined in <sys/time.h> and look like
这个复杂的时间结构体定义在<sys/time.h>中,类似于

           struct timeval {
               long    tv_sec;         /* seconds */
               long    tv_usec;        /* microseconds */
           };

       and

           struct timespec {
               long    tv_sec;         /* seconds */
               long    tv_nsec;        /* nanoseconds */
           };

       (However, see below on the POSIX.1-2001 versions.)

       Some code calls select() with all three sets empty, nfds zero, and a non-NULL
       timeout as a fairly portable way to sleep with subsecond precision.
(然而,下面的是POSIX.1-2001版本)
一些代码调用 select() 的所有标志位都为空,而nfds 为0,和一个非零的timeout 来作为相当轻便的休眠一个亚秒时间精确度.

       On Linux, select() modifies timeout to reflect the amount of time not slept;
       most other implementations do not do this.  (POSIX.1-2001 permits either
       behavior.)  This causes problems both when Linux code which reads timeout is
       ported to other operating systems, and when code is ported to Linux that
       reuses a struct timeval for multiple select()s in a loop without
       reinitializing it.  Consider timeout to be undefined after select() returns.
在Linux,select() 修改 timeout 来反映出没有休眠的时间;很多其他的程序并不这样做(POSIX.1-2001版本允许这2种行为).当Linux的代码到了别的操作系统中,和在一个循环中的多个select()的struct timeval 重用时都未初始化的代码用在了Linux中,就会产生问题.所以就将timeoutselect()返回后就当作是未定义的就好.

 

RETURN VALUE

       On success, select() and pselect() return the number of file descriptors
       contained in the three returned descriptor sets (that is, the total number of
       bits that are set in readfds, writefds, exceptfds) which may be zero if the
       timeout expires before anything interesting happens.  On error, -1 is
       returned, and errno is set appropriately; the sets and timeout become
       undefined, so do not rely on their contents after an error.

成功的话,select() 和 pselect() 都返回在3个描述数组中的fd数目,也可能为0,一旦超时在我们感兴趣的事情发生事前到期.

错误的话,返回-1并自动设置errno .标志位的timeout 变为未定义的,所以不要以来错误后的返回值.

ERRORS

       EBADF  An invalid file descriptor was given in one of the sets.  (Perhaps a
              file descriptor that was already closed, or one on which an error has
              occurred.)
       EINTR  A signal was caught; see signal(7).

       EINVAL nfds is negative or the value contained within timeout is invalid.

       ENOMEM unable to allocate memory for internal tables.

 EBADF  : 一个无效的fd给了标志位.(可能一个fd已经关闭了,或者已经发生了错误)

 EINTR  : 信号产生了中断

 EINVAL : nfds 是负数或者在timeout 中包含的值是无效的

 ENOMEM : 不能为内部的列表分配内存

VERSIONS

       pselect() was added to Linux in kernel 2.6.16.  Prior to this, pselect() was
       emulated in glibc (but see BUGS).

 pselect() 在Linux 2.6.16之后加入进来,再早一点的话,在glibc有类似的实现.

CONFORMING TO

       select() conforms to POSIX.1-2001 and 4.4BSD (select() first appeared in
       4.2BSD).  Generally portable to/from non-BSD systems supporting clones of the
       BSD socket layer (including System V variants).  However, note that the System
       V variant typically sets the timeout variable before exit, but the BSD variant
       does not.

pselect() is defined in POSIX.1g, and in POSIX.1-2001.

select() 符合POSIX.1-2001 和 4.4BSD (select() 第一次出现4.2BSD).select() 支持一般的轻量的非BSD系统支持BSD socket层(包括System V的变种)的副本.然后值得注意的是:System V变种一般都在select() 退出前设置超时值;而BSD变种则不这样做.

NOTES

       An fd_set is a fixed size buffer.  Executing FD_CLR() or FD_SET() with a value
       of fd that is negative or is equal to or larger than FD_SETSIZE will result in
       undefined behavior.  Moreover, POSIX requires fd to be a valid file
       descriptor.
fd_set 是固定大小的缓存.使用负数或者大小等于FD_SETSIZE 的fd进行FD_CLR() 或 FD_SET() 操作将带来不可预计的行为.而且,POSIX需要fd 为一个有效的值.
       Concerning the types involved, the classical situation is that the two fields
       of a timeval structure are typed as long (as shown above), and the structure
       is defined in <sys/time.h>.  The POSIX.1-2001 situation is

           struct timeval {
               time_t         tv_sec;     /* seconds */
               suseconds_t    tv_usec;    /* microseconds */
           };

       where the structure is defined in <sys/select.h> and the data types time_t and
       suseconds_t are defined in <sys/types.h>.
关于复杂的类型,典型的情况是timeval 的2个成员为long 型(就像上面的),结构体定义在<sys/time.h> , POSIX.1-2001 的情况是:结构体定义在<sys/select.h> time_tsuseconds_t 定义在<sys/types.h>中. 
       Concerning prototypes, the classical situation is that one should include
       <time.h> for select().  The POSIX.1-2001 situation is that one should include
       <sys/select.h> for select() and pselect().
关于原型,典型的情况是使用 select() 应该包含 <time.h>. POSIX.1-2001 的情况是使用 select() 和 pselect() 应该包含 <sys/select.h> . 
       Libc4 and libc5 do not have a <sys/select.h> header; under glibc 2.0 and later
       this header exists.  Under glibc 2.0 it unconditionally gives the wrong
       prototype for pselect().  Under glibc 2.1 to 2.2.1 it gives pselect() when
       _GNU_SOURCE is defined.  Since glibc 2.2.2 the requirements are as shown in
       the SYNOPSIS.
Libc4 和 Libc5 没有 <sys/select.h> 这个头文件,只在 glibc 2.0 和之后的有这个头文件.使用pselect() 在2.0 的 glibc 会无条件的给出错误原型.在 glibc 2.1 到 2.2 当_GNU_SOURCE 定义的时候,有 pselect()  的定义.直到 glibc 2.2.2 中才在摘要中显示.

Linux Notes

       The Linux pselect() system call modifies its timeout argument.  However, the
       glibc wrapper function hides this behavior by using a local variable for the
       timeout argument that is passed to the system call.  Thus, the glibc pselect()
       function does not modify its timeout argument; this is the behavior required
       by POSIX.1-2001.

pselect() 系统调用会修改timeout 参数,然而 gilibc 通过对timeout 参数使用一个局部变量来传递给系统调用这种形式的封装函数来隐藏这一行为.这样, glibc 的 pselect() 就不会修改timeout 参数,这正是  POSIX.1-2001 需要的行为.

BUGS

       Glibc 2.0 provided a version of pselect() that did not take a sigmask
       argument.
Glibc 2.0 提供了一个不使用 sigmask 参数的 pselect() 版本.
       Starting with version 2.1, glibc provided an emulation of pselect() that was
       implemented using sigprocmask(2) and select().  This implementation remained
       vulnerable to the very race condition that pselect() was designed to prevent.
       Modern versions of glibc use the (race-free) pselect() system call on kernels
       where it is provided.
从Glibc 2.1 开始,glibc 通过使用 sigpromask() 提供 pselect() 的竞争者.sigpromask() 保留了pselect() 非常想避免的竞争情况作为弱点.现代版本的 glibc 在内核中使用非竞争的 pselect() 调用.
       On systems that lack pselect(), reliable (and more portable) signal trapping
       can be achieved using the self-pipe trick (where a signal handler writes a
       byte to a pipe whose other end is monitored by select() in the main program.)
当系统缺少pselect() 时, 通过使用self-pipe 谋略(在linux环境高级编程中有描述,具体位置在poll()和select()附近)(在main()函数中,一个信号处理程序向一个管道写一个字节而管道的另一端被 select() 所监视)能够产生可靠的(更加轻量的)的信号陷阱.
       Under Linux, select() may report a socket file descriptor as "ready for
       reading", while nevertheless a subsequent read blocks.  This could for example
       happen when data has arrived but upon examination has wrong checksum and is
       discarded.  There may be other circumstances in which a file descriptor is
       spuriously reported as ready.  Thus it may be safer to use O_NONBLOCK on
       sockets that should not block.
在linux下, select()  可能报告一个socket fd 为可读的, 但是后来的读取会被阻塞.举例说明这是可能发生的,当数据到达了但是经过审查是错误的校验并抛弃的时候.可能另一个可能是fd伪造成为可读的.这样,在一个不应该被阻塞的socket上使用O_NONBLOCK 就是安全的.
       On Linux, select() also modifies timeout if the call is interrupted by a
       signal handler (i.e., the EINTR error return).  This is not permitted by
       POSIX.1-2001.  The Linux pselect() system call has the same behavior, but the
       glibc wrapper hides this behavior by internally copying the timeout to a local
       variable and passing that variable to the system call.

在linux下,如果 select() 调用被信号打断的话也会修改timeout 参数的(如 EINTR 返回的时候).但这在 POSIX.1-2001 中是不允许的.Linux 的 pselect() 系统调用也有相同的行为,但是glibc 通过将timeout  拷贝得到局部变量的方式传递给系统调用的封装来隐藏这种行为

EXAMPLE

#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> int main(void) { fd_set rfds; struct timeval tv; int retval; /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait up to five seconds. */ tv.tv_sec = 5; tv.tv_usec = 0; retval = select(1, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1) perror("select()"); else if (retval) printf("Data is available now./n"); /* FD_ISSET(0, &rfds) will be true. */ else printf("No data within five seconds./n"); exit(EXIT_SUCCESS); }

 

SEE ALSO

       For a tutorial with discussion and examples, see select_tut(2).

       For vaguely related stuff, see accept(2), connect(2), poll(2), read(2),
       recv(2), send(2), sigprocmask(2), write(2), epoll(7), time(7)

 

COLOPHON

       This page is part of release 3.29 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                                 2010-08-31                            SELECT(2)

你可能感兴趣的:(Linux socket Select(2) (翻译 man 2))