• Linux IO多路复用 poll


    Linux IO多路复用 poll

    之前曾经提到过 select

    poll 跟select类似,poll改进了select的一个确定,就是poll没有监听上限

    不过poll还是需要遍历以及频繁的把数组拷贝到内核空间,在监听较多文件描述符的时候性能会下降

    #include <poll.h>
    
    int poll(struct pollfd *fds, nfds_t nfds, int timeout);
    

    传递的三个参数

    fds:结构体数组

    nfds:监听数量,(select 是最大文件描述符的值)

    timeout:超时时间

    我们再来看一下这个结构体

    struct pollfd {
        int   fd;         /* file descriptor */
        short events;     /* requested events */
        short revents;    /* returned events */
    };
    

    第一个fd肯定是要监听的文件描述符

    第二个是期望监听的事件

    第三个是返回的事件

    事件的具体定义在 poll.h

    可以同时监听多个事件

    //具体可见 bits/poll.h
    #define POLLIN          0x001           /* There is data to read.  */
    #define POLLPRI         0x002           /* There is urgent data to read.  */
    #define POLLOUT         0x004           /* Writing now will not block.  */
    

    这几个只要按位或就可以监听多个数据了

    当poll返回的时候,我们也可以test事件(按位与),不过需要对数组进行遍历

    RETURN VALUE
    On success, a positive number is returned; this is the number of struc‐
    tures which have nonzero revents fields (in other words, those descrip‐
    tors with events or errors reported). A value of 0 indicates that the
    call timed out and no file descriptors were ready. On error, -1 is
    returned, and errno is set appropriately.

    调用成功的时候返回一个正数(监听就绪结构体的数量),-1出错,他会设置errno,0是超时,没有文件名准备好

    poll简单来讲跟select差不多,都是同步非阻塞,效率都不是很高,一般都是用epoll代替,不过poll把结构体拷贝到内核空间的时候好像是用链表表示的,所以没有上限,但是涉及到巨量拷贝效率还是很低,使用的时候还是要遍历,我并没有看源码,挖个坑有机会补一下

    实例可以参考下面这个链接,这里挖个坑,以后再补

    https://www.cnblogs.com/Anker/p/3261006.html

    同步异步不过不太清楚的可以具体看看这个文章,写的很好

    https://www.cnblogs.com/euphie/p/6376508.html

  • 相关阅读:
    TCHAR转化为UTF8
    Chromium ID 计算方法
    构建之法感悟
    项目名称:上海地铁游
    统一入口的Ajax验证
    基于用户体验的服务型政府网站群建设优化方案
    新技术下的政府门户网站群建设建议
    国内CMS技术发展的外在表现形式
    JavaScript基础 BOM
    JavaScript基础 常见DOM树操作
  • 原文地址:https://www.cnblogs.com/stdpain/p/10658119.html
Copyright © 2020-2023  润新知