epoll 使用实例

原文:http://blog.csdn.net/force_eagle/article/details/4348017

epoll网上g一大把, 就不详细叙述了.

推荐几篇好文章:

epoll精髓

epoll相关资料整理

epoll LT VS ET

epoll(7) - Linux man page

EPOLL为我们带来了什么

  1. #include <stdio.h>   
  2. #include <unistd.h>   
  3. #include <errno.h>   
  4. #include <time.h>   
  5. #include <sys/time.h>   
  6. #include <signal.h>   
  7. #include <poll.h>   
  8. #include <sys/types.h>   
  9. #include <error.h>   
  10.   
  11. void call_poll(void)  
  12. {  
  13.     struct pollfd fds;  
  14.     int32_t timeout_msecs = 5000;  
  15.     int err;  
  16.       
  17.     fds.fd = 1;  
  18.     fds.events = POLLIN | POLLPRI ;  
  19.     err = poll( &fds, 1, timeout_msecs );  
  20.     if ( err > 0 ) {  
  21.         printf("Data is available now./n");  
  22.     }  
  23.     else if ( err == 0 ) {  
  24.         printf("No data within five seconds./n");  
  25.     }  
  26.     else  {  
  27.         perror( "poll()" );  
  28.     }  
  29.   
  30. }  
  31. #include <sys/epoll.h>   
  32.   
  33. void call_epoll(void)  
  34. {  
  35.     int epfd;  
  36.     struct epoll_event ev_stdin;  
  37.     int err;  
  38.   
  39.     epfd = epoll_create(1);  
  40.     if ( epfd < 0 ) {  
  41.         perror( "epoll_create()" );  
  42.         return ;  
  43.     }  
  44.   
  45.     bzero( &ev_stdin, sizeofstruct epoll_event) );  
  46.     ev_stdin.events =   
  47.         //  available for read operations   
  48.         EPOLLIN | EPOLLPRI   
  49.         // available for write operations   
  50.         // | EPOLLOUT    
  51.         // Error condition && Hang up happened    
  52.         | EPOLLERR | EPOLLHUP   
  53.         // Sets the Edge Triggered behaviour    
  54.         | EPOLLET   
  55.         // Sets the one-shot behaviour.    
  56.         // must call epoll_ctl with EPOLL_CTL_MOD to re-enable   
  57.         | EPOLLONESHOT   
  58.         ;  
  59.   
  60.     err = epoll_ctl( epfd, EPOLL_CTL_ADD, 1, &ev_stdin );  
  61.     if ( err < 0 ) {  
  62.         perror( "epoll_ctl()" );  
  63.         goto _out;  
  64.     }  
  65.     err = epoll_wait( epfd, &ev_stdin, 1, 5000 );  
  66.     if ( err < 0 ) {  
  67.         perror( "epoll_wait()" );  
  68.     }  
  69.     else if ( err == 0 ) {  
  70.         printf("No data within five seconds./n");  
  71.     }  
  72.     else {  
  73.          printf("Data is available now./n");  
  74.     }  
  75.     //err = epoll_ctl( epfd, EPOLL_CTL_DEL, 1, &ev_stdin );   
  76.     //   
  77.     err = epoll_ctl( epfd, EPOLL_CTL_DEL, 1, &ev_stdin );  
  78.     if ( err < 0 ) {  
  79.         perror( "epoll_ctl()" );  
  80.     }  
  81. _out:  
  82.     close( epfd );  
  83. }  
  84. int main ()  
  85. {  
  86.     call_epoll();  
  87.     return 0;  
  88. }  

 

阅读(274) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/black/p/5171747.html