最近想研究下 libev 这个网络库,所以先从官方文档一个最简单的 demo 开始,代码如下:

//io.c
// a single header file is required
#include <ev.h>
#include <stdio.h> // for puts
// every watcher type has its own typedef'd struct
// with the name ev_TYPE
ev_io stdin_watcher;
ev_timer timeout_watcher;
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void stdin_cb (EV_P_ ev_io *w, int revents) {
puts ("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop (EV_A_ w);
// this causes all nested ev_run's to stop iterating
ev_break (EV_A_ EVBREAK_ALL);
}
// another callback, this time for a time-out
static void timeout_cb (EV_P_ ev_timer *w, int revents) {
puts ("timeout");
// this causes the innermost ev_run to stop iterating
ev_break (EV_A_ EVBREAK_ONE);
} int main (void) {
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init (&stdin_watcher, stdin_cb,
/* STDIN_FILENO*/ , EV_READ);
ev_io_start (loop, &stdin_watcher);
// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, .);
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_run (loop, );
// break was called, so exit
return ;
}

编译并运行:

gcc -c -o io.o io.c
gcc -o io io.o -lev $ ./io
$ timeout
$ ./io
$
$ stdin ready

编译的时候需要链接 libev 动态库。

从上面可以看出,我是运行了这个程序两次。第一次是运行后就不再执行任何操作, 等待程序自己因为超时而结束。第二次就是按了一个回车,使 stdin 处于可读状态,触发了 io 事件, 程序也结束了。

可以说这代码非常容易理解,代码间的注视也是非常的详细。

以后会对 libev 的具体数据结果和实现进行分析。这个 demo 就到这里啦。


同步地址:http://www.fengbohello.top/code/libev-001

最新文章

  1. Access提示“操作必须使用一个可更新的查询”的解决办法
  2. Android Studio NDK初探
  3. linux通过ntp设置系统时间
  4. JavaScript语言精粹学习笔记
  5. 根据不同的实体及其ID来获取数据库中的数据
  6. (5) 深入理解Java Class文件格式(四)
  7. WorldWind源码剖析系列:WorldWind如何确定与视点相关的地形数据的LOD层级与范围
  8. struts2框架——从后台取得数据集,并在前台页面循环显示
  9. ThinkPHP 学习笔记 ( 三 ) 数据库操作之数据表模型和基础模型 ( Model )
  10. [翻译][MVC 5 + EF 6] 11:实现继承
  11. xmlns:tools=&quot;http://schemas.android.com/tools&quot;以及tools:context=&quot;.ConfActivity&quot;是什么意思
  12. Spring自学教程-注解的使用(三)
  13. python查询完结篇
  14. python学习笔记(1)python中的注释和安装python
  15. https遇到自签名证书/信任证书
  16. Oracl数据库+PL/SQL安装与配置
  17. spark streaming将处理结果存入mysql中(使用c3p0连接池)
  18. Python学习--和 Oracle 交互(2)
  19. Python Web学习笔记之TCP、UDP、ICMP、IGMP的解释和区别
  20. Linux-JDK+Tomcat的安装笔记

热门文章

  1. 不利用C语言库函数,实现字符串相关函数
  2. 将linux系统目录挂载到其他分区,扩大系统可用空间
  3. hexo添加404公益界面
  4. Nginx访问权限配置
  5. 实现DataGridView控件中CheckBox列的使用
  6. opencv3 学习笔记(二)
  7. [OC] Block的使用
  8. SpringMVC的请求处理流程
  9. 初窥Java--2(下载Eclipse,安装tomcat插件)
  10. websocket是什么