epoll 使用实例

本文深入探讨了epoll的工作原理及其实现方式,并通过代码示例展示了如何使用epoll进行I/O多路复用,包括epoll_create、epoll_ctl和epoll_wait等关键函数的应用。

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

推荐几篇好文章:

epoll精髓

epoll相关资料整理

epoll LT VS ET

epoll(7) - Linux man page

EPOLL为我们带来了什么

#include <stdio.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <signal.h> #include <poll.h> #include <sys/types.h> #include <error.h> void call_poll(void) { struct pollfd fds; int32_t timeout_msecs = 5000; int err; fds.fd = 1; fds.events = POLLIN | POLLPRI ; err = poll( &fds, 1, timeout_msecs ); if ( err > 0 ) { printf("Data is available now.\n"); } else if ( err == 0 ) { printf("No data within five seconds.\n"); } else { perror( "poll()" ); } } #include <sys/epoll.h> void call_epoll(void) { int epfd; struct epoll_event ev_stdin; int err; epfd = epoll_create(1); if ( epfd < 0 ) { perror( "epoll_create()" ); return ; } bzero( &ev_stdin, sizeof( struct epoll_event) ); ev_stdin.events = // available for read operations EPOLLIN | EPOLLPRI // available for write operations // | EPOLLOUT // Error condition && Hang up happened | EPOLLERR | EPOLLHUP // Sets the Edge Triggered behaviour | EPOLLET // Sets the one-shot behaviour. // must call epoll_ctl with EPOLL_CTL_MOD to re-enable | EPOLLONESHOT ; err = epoll_ctl( epfd, EPOLL_CTL_ADD, 1, &ev_stdin ); if ( err < 0 ) { perror( "epoll_ctl()" ); goto _out; } err = epoll_wait( epfd, &ev_stdin, 1, 5000 ); if ( err < 0 ) { perror( "epoll_wait()" ); } else if ( err == 0 ) { printf("No data within five seconds.\n"); } else { printf("Data is available now.\n"); } //err = epoll_ctl( epfd, EPOLL_CTL_DEL, 1, &ev_stdin ); // err = epoll_ctl( epfd, EPOLL_CTL_DEL, 1, &ev_stdin ); if ( err < 0 ) { perror( "epoll_ctl()" ); } _out: close( epfd ); } int main () { call_epoll(); return 0; }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值