Skip to content
On this page

select(2)


标签:linux/conc  

函数原型

功能:实现 IO 多路复用,参考 select

在执行 select 之后,fds 只会剩下有事件的文件描述符。

c
/* According to POSIX.1-2001, 
POSIX.1-2008 */ 
#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,
      const struct timespec *timeout)

参数:

  • int nfds:集合中最大的文件描述符 + 1
  • fd_set *readfds...:读集合,写集合,其他集合。如果用不上填写 NULL
  • struct timeval *timeout:设置超时时间:
    1. NULL:代表不设置超时时间,该函数会一直阻塞,直到文件描述符准备就绪,解除阻塞
    2. 设置超时时间:时间到了以后,依然没有文件描述符准备就绪,则函数会立即返回失败情况
c
struct timeval {
  long tv_sec;     /* seconds */
  long tv_usec;    /* microseconds */
}

返回值:

  • > 0:成功返回成功触发时间的文件描述符的个数
  • = 0:超时了
  • - 1:函数允许失败,更新 errno

fd_set

文件描述符集合,定义参考:sys/select.h

宏函数

  • void FD_CLR: 将 fd 从集合中删除
  • int FD_ISSET:判断 fd 是否在合集中,如果在返回真
  • void FD_SET:将 fd 添加到集合中
  • void FD_ZERO: 将合集清空

Last updated: