先从一个 libev 的 demo 入手
2017-07-09 01:40
447 查看
最近想研究下 libev 这个网络库,所以先从官方文档一个最简单的 demo 开始,代码如下:
编译并运行:
编译的时候需要链接 libev 动态库。
从上面可以看出,我是运行了这个程序两次。第一次是运行后就不再执行任何操作, 等待程序自己因为超时而结束。第二次就是按了一个回车,使 stdin 处于可读状态,触发了 io 事件, 程序也结束了。
可以说这代码非常容易理解,代码间的注视也是非常的详细。
以后会对 libev 的具体数据结果和实现进行分析。这个 demo 就到这里啦。
同步地址:http://www.fengbohello.top/code/libev-001
//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*/ 0, 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, 0.); ev_timer_start (loop, &timeout_watcher); // now wait for events to arrive ev_run (loop, 0); // break was called, so exit return 0; }
编译并运行:
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
相关文章推荐
- Sencha Touch 1.1.1 之初接触(一)怎样入手并写一个漂亮的demo[转]
- WCF+WF双剑合璧构建微软的SOA系列(一):从一个简单的Demo开始
- Sencha Touch 1.1.1 之初接触(一)怎样入手并写一个漂亮的demo
- 从一个简单的WEB项目入手来简单地了解一下什么是Spring之持久层(Dao)
- android网络开源框架volley(一)——从一个demo开始
- 从一个真实项目入手分析测试有效性
- 从一个demo引发的对import、require的思考
- android新开发语言Kotlin的入手Demo
- Sencha Touch 1.1.1 之初接触(一)怎样入手并写一个漂亮的demo
- Sencha Touch 1.1.1 之初接触(一)怎样入手并写一个漂亮的demo
- 从一个小demo开始,体验“API经济”的大魅力
- [小北De编程手记] Lesson 01 - AutoFramework构建 之 从一个简单的Demo聊起
- WCF+WF双剑合璧构建微软的SOA系列(一):从一个简单的Demo开始
- [转]WCF+WF双剑合璧构建微软的SOA系列(一):从一个简单的Demo开始
- 从实例入手,讲解 CMake 的常见用法。demo1-demo8
- Android自定义权限(从一个Demo主界面跳转到另外一个Demo的主界面)、及四大组件的声明
- Netty源码:从一个简单Demo开始
- 从一个小demo开始,体验“API经济”的大魅力
- 从一个Demo,学会hourglass三种用法
- 一起谈.NET技术,WCF+WF双剑合璧构建微软的SOA系列(一):从一个简单的Demo开始