1. The select function
#include <sys/select.h>
int select(int maxfd
, fd_set* readset, fd_set* writeset, fd_set* exceptset
, const struct timeval* timeout);
Description:
- It returns greater than 0 on success, -1 on failure, and 0 on timeout
- maxfd Number of file descriptors to be monitored
- readset registers a collection of file descriptors for reading data
- writeset Register a collection of file descriptors for writing data
- exceptset registers a collection of exception file descriptors
- timeout call select function, program block, set program block timeout time
Role: to monitor multiple file descriptors together.
2. Use
Assignment method of fd_set type object:
FD_ZERO(fd_set* fdset): 将fd_set变量的所有位初始化为0。
FD_SET(int fd, fd_set* fdset):在参数fd_set指向的变量中注册文件描述符fd的信息。
FD_CLR(int fd, fd_set* fdset):参数fd_set指向的变量中清除文件描述符fd的信息。
FD_ISSET(int fd, fd_set* fdset):若参数fd_set指向的变量中包含文件描述符fd的信息,则返回真。
3. Example
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/select.h>
#define BUF_SIZE 30
int main(int argc, char const *argv[])
{
fd_set reads;
fd_set temps;
FD_ZERO(&reads);
FD_SET(0, &reads); // 0 是控制台标准输入文件描述符,1 是标准输出描述符,2 是异常描述符
while (1)
{
temps = reads;
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
int result = select(1, &temps, NULL, NULL, &timeout);
if (result == -1) // 发生异常
{
puts("select() error!");
break;
}
else if (result == 0) // 监听描述符事件超时
{
puts("time-out!");
}
else
{
if (FD_ISSET(0, &temps)) // 判断0描述符输入事件是否发生
{
char buf[BUF_SIZE];
int str_len = read(0, buf, BUF_SIZE);
buf[str_len] = 0;
printf("message from console: %s\n", buf);
}
}
}
return 0;
}