Linux select内核源码剖析

IO多路复用接口Linux内核源码剖析,源码之前,了无秘密

Linux poll内核源码剖析

Linux select内核源码剖析

Linux epoll内核源码剖析

Linux select内核源码剖析


select的原理其实是和poll是一样的,都是采用轮询的方式。select相对于poll也许是比较节省空间吧,因为select是采用bitmap来标志的

本文先讲解一下如何在应用层使用select,然后再深入内核剖析select机制

select应用程序

select可以监听多个文件描述符,直到条件满足或者超时返回

  • select函数原型

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

    nfds:最大的文件描述符加1

    readfds:监听可读集合

    writefds:监听可写集合

    exceptfds:监听异常集合

    timeout:超时时间

    对于这些集合,有一组函数可以进行设置

    void FD_SET(int fd, fd_set *set); //设置文件描述符到集合中
    void FD_CLR(int fd, fd_set *set); //从集合中清除文件描述符标志
    int  FD_ISSET(int fd, fd_set *set); //判断文件描述符在集合中是否被标志
    void FD_ZERO(fd_set *set); //清空集合
    

demo

下面这个程序使用select监听标准输入,直到标准输入可读时,返回并打印内容

#include <stdio.h>
#include <sys/select.h>

int main(int argc, char* argv[])
{
   
    fd_set rfds;
    int nfds;
    int i;
    char buf[1024];
    int len;

    FD_ZERO(&rfds); //清空集合

    FD_SET(0, &rfds); //标准输入
    nfds = 0 + 1; //最大文件描述符加1

    while(1)
    {
   
        fd_set fds = rfds;
        
        /* 开始监听 */
        if(select(nfds, &fds, NULL, NULL, NULL) < 0)
        {
   
            printf("select err.\n");
            return -1;
        }

        for(i = 0; i < nfds
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值