Linux socket之四:使用POLL机制处理多连接

来源:互联网 发布:西门子plc伺服编程 编辑:程序博客网 时间:2024/04/30 01:25

使用select函数可以处理socket多连接的问题(select的用法参见:http://blog.csdn.net/zhandoushi1982/article/details/5070107),使用POLL也可以实现同样的功能,且调用方式更加简单。原型是:

[cpp] view plain copy
  1. struct pollfd {  
  2.  int fd;        //文件描述符  
  3.  short events;  //要求查询的事件掩码  
  4.  short revents; //返回的事件掩码  
  5. };  
  6. int poll(struct pollfd *ufds, unsigned int nfds, int timeout);  

         poll函数使用pollfd类型的结构来监控一组文件句柄,ufds是要监控的文件句柄集合,nfds是监控的文件句柄数量,timeout是等待的毫秒数,这段时间内无论I/O是否准备好,poll都会返回。timeout为负数表示无线等待,timeout为0表示调用后立即返回。执行结果:为0表示超时前没有任何事件发生;-1表示失败;成功则返回结构体中revents不为0的文件描述符个数。pollfd结构监控的事件类型如下:

[cpp] view plain copy
  1. #define POLLIN 0x0001  
  2. #define POLLPRI 0x0002  
  3. #define POLLOUT 0x0004  
  4. #define POLLERR 0x0008  
  5. #define POLLHUP 0x0010  
  6. #define POLLNVAL 0x0020  
  7.   
  8. #define POLLRDNORM 0x0040  
  9. #define POLLRDBAND 0x0080  
  10. #define POLLWRNORM 0x0100  
  11. #define POLLWRBAND 0x0200  
  12. #define POLLMSG 0x0400  
  13. #define POLLREMOVE 0x1000  
  14. #define POLLRDHUP 0x2000  

      如上是events事件掩码的值域,POLLIN|POLLPRI类似于select的读事件,POLLOUT|POLLWRBAND类似于select的写事件。当events属性为POLLIN|POLLOUT,表示监控是否可读或可写。在poll返回时,即可通过检查revents变量对应的标志位与events是否相同,比如revents中POLLIN事件标志位被设置,则表示文件描述符可以被读取。代码段示例:

[cpp] view plain copy
  1. int sockfd;             //套接字句柄  
  2. struct pollfd pollfds;  
  3. int timeout;  
  4.   
  5. timeout = 5000;  
  6. pollfds.fd = sockfd;                //设置监控sockfd  
  7. pollfds.events = POLLIN|POLLPRI;            //设置监控的事件  
  8.   
  9. for(;;){  
  10.     switch(poll(&pollfds,1,timeout)){       //开始监控  
  11.     case -1:                    //函数调用出错  
  12.         printf("poll error \r\n");  
  13.     break;  
  14.     case 0:  
  15.         printf("time out \r\n");  
  16.     break;  
  17.     default:                    //得到数据返回  
  18.         printf("sockfd have some event \r\n");  
  19.         printf("event value is 0x%x",pollfds.revents);  
  20.     break;  
  21.     }  
  22. }   
0 0
原创粉丝点击