先從一個 libev 的 demo 入手

最近想研究下 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*/ 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;
}

編譯並運行:less

gcc -c -o io.o io.c
gcc -o io io.o -lev

$ ./io 
$ timeout
$ ./io 
$
$ stdin ready

編譯的時候須要連接 libev 動態庫。oop

從上面能夠看出,我是運行了這個程序兩次。第一次是運行後就再也不執行任何操做, 等待程序本身由於超時而結束。第二次就是按了一個回車,使 stdin 處於可讀狀態,觸發了 io 事件, 程序也結束了。ui

能夠說這代碼很是容易理解,代碼間的注視也是很是的詳細。this

之後會對 libev 的具體數據結果和實現進行分析。這個 demo 就到這裏啦。spa


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

相關文章
相關標籤/搜索