linux poll操作

来源:互联网 发布:支付宝绑定多个淘宝号 编辑:程序博客网 时间:2024/06/10 18:43
2009-03-31 19:31

poll和sellect实现功能差不多,但poll效率高,以后要多用poll

poll()接受一个指向结构'struct pollfd'列表的指针,其中包括了你想测试的文件描述符和事件。事件由一个在结构中事件域的比特掩码确定。当前的结构在调用后将被填写并在事件发生后返回。在SVR4(可能更早的一些版本)中的 "poll.h"文件中包含了用于确定事件的一些宏定义。事件的等待时间精确到毫秒 (但令人困惑的是等待时间的类型却是int),当等待时间为0时,poll()函数立即返回,-1则使poll()一直挂起直到一个指定事件发生。下面是pollfd的结构。

      struct pollfd {
          int fd;         /* 文件描述符 */
          short events;   /* 等待的事件 */
          short revents; /* 实际发生了的事件 */
      };
      
于select()十分相似,当返回正值时,代表满足响应事件的文件描述符的个数,如果返回0则代表在规定事件内没有事件发生。如发现返回为负则应该立即查看 errno,因为这代表有错误发生。

如果没有事件发生,revents会被清空,所以你不必多此一举。

这里是一个例子

    /* 检测两个文件描述符,分别为一般数据和高优先数据。如果事件发生
       则用相关描述符和优先度调用函数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);
        }
    }
     


原创粉丝点击