epoll技术,及其常用操作

 
http://blog.chinaunix.net/u/14063/showart_377118.html (epoll技术的介绍)
void addEpoll(int kdpfd, __uint32_t events, void *ptr)
{
mutex.lock;
_ev.events = events; //这里的events是由EPOLLIN | EPOLLOUT | EPOLLPRI等等的或取得
_ev.data.ptr = ptr;
if(-1 == epoll_ctl(kdpfd, EPOLL_CTL_ADD, sock, &_ev))//可以做各种操作
{//错误处理
}
mutex.unlock();
}
备注1:_ev的类型为struct epoll_event _ev; kdpfd是epoll的句柄。可以man epoll_ctl来查看各个参数及数据结构.
­
如何使用int poll(struct pollfd *ufds, unsigned int nfds, int timeout)呢
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);      
     }  
}

你可能感兴趣的:(epoll技术,及其常用操作)