找回密码
 注册
搜索
热搜: 超星 读书 找书
查看: 2034|回复: 0

[【推荐】] epoll 使用实例

[复制链接]
发表于 2009-8-6 14:23:27 | 显示全部楼层 |阅读模式
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, sizeof( struct 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. }
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|网上读书园地

GMT+8, 2024-6-9 13:52 , Processed in 0.355961 second(s), 4 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表