I/O复用select函数的简单用法

1、select函数

#include <sys/select.h>

int select(int maxfd
         , fd_set* readset, fd_set* writeset, fd_set* exceptset
         , const struct timeval* timeout);

说明:

  • 成功时返回大于0,失败返回-1,超时返回时返回0
  • maxfd 监视对象文件描述符数量
  • readset 注册读数据文件描述符的集合
  • writeset 注册写数据文件描述符的集合
  • exceptset 注册异常文件描述符的集合
  • timeout 调用select函数,程序阻塞,设定程序阻塞超时时间

作用:将多个文件描述符集中到一起监视。

2、使用

fd_set类型对象的赋值方式:

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、示例

#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;
}

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/109430930