poll函数用户态全面分析


用户层:

 

poll()函数通过检验一组文件描述符来检测是否有特定的时间将在上面发生并在一定的时间内等待其发生。 

 

poll()接受一个指向结构"struct pollfd"列表的指针,其中包括了你想测试的文件描述符和事件。事件由一个在结构中事件域的比特掩码确定。当前的结构在调用后将被填写并在事件发生后返回。

 

当等待时间为0时,poll()函数立即返回,-1则使poll()一直挂起直到一个指定事件发生。下面是pollfd的结构。 

 

      struct pollfd {

          int fd;         /* 文件描述符 */

          short events;   /* 等待的事件 */

          short revents; /* 实际发生了的事件 */

      };

 

当返回正值时,代表满足响应事件的文件描述符的个数,如果返回0则代表在规定事件内没有事件发生。如发现返回为负则应该立即查看 errno,因为这代表有错误发生。

 

重要事项:无论select()还是poll()都不对普通文件起很大效用,它们着重用于套接口(socket)、管道(pipe)、伪终端(pty)、终端设备(tty)和其他一些字符设备,但是这些操作都是系统相关(system-dependent)的。

 

 

这里是一个例子 

 

    /* 检测两个文件描述符,分别为一般数据和高优先数据。如果事件发生

       则用相关描述符和优先度调用函数handler(),无时间限制等待,直到

       错误发生或描述符挂起。*/

   

    #include <stdlib.h>

    #include <stdio.h>

 

 

    #include <sys/types.h>

    #include <stropts.h>

    #include <poll.h>

  

    #include <unistd.h>

    #include <errno.h>

    #include <string.h>

  

    #define NORMAL_DATA 1

    #define HIPRI_DATA 2

  

    int poll_two_normal(int fd1,int fd2)

    {

        struct pollfd poll_list[2];

        int retval;

  

        poll_list[0].fd = fd1;

        poll_list[1].fd = fd2;

        poll_list[0].events = POLLIN|POLLPRI;

        poll_list[1].events = POLLIN|POLLPRI;

  

        while(1)

        {

            retval = poll(poll_list,(unsigned long)2,-1);

            /* retval 总是大于0或为-1,因为我们在阻塞中工作 */

  

            if(retval < 0)

            {

                fprintf(stderr,"poll错误: %s\n",strerror(errno));

                return -1;

            }

    

            if(((poll_list[0].revents&POLLHUP) == POLLHUP) ||

               ((poll_list[0].revents&POLLERR) == POLLERR) ||

               ((poll_list[0].revents&POLLNVAL) == POLLNVAL) ||

               ((poll_list[1].revents&POLLHUP) == POLLHUP) ||

               ((poll_list[1].revents&POLLERR) == POLLERR) ||

               ((poll_list[1].revents&POLLNVAL) == POLLNVAL))

              return 0;

  

            if((poll_list[0].revents&POLLIN) == POLLIN)

              handle(poll_list[0].fd,NORMAL_DATA);

            if((poll_list[0].revents&POLLPRI) == POLLPRI)

              handle(poll_list[0].fd,HIPRI_DATA);

            if((poll_list[1].revents&POLLIN) == POLLIN)

              handle(poll_list[1].fd,NORMAL_DATA);

            if((poll_list[1].revents&POLLPRI) == POLLPRI)

              handle(poll_list[1].fd,HIPRI_DATA);

        }

    }

原文地址:https://www.cnblogs.com/wangxianzhen/p/3081682.html