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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值