close

Libev是一個用C編寫的功能齊全的高性能的羽量級事件驅動庫,其支援多種後臺IO複用介面,並且可以註冊多達十幾種事件。

支援的後臺IO複用介面:

select
poll
epoll
kqueue
solaris event port

支援的事件類型:

ev_io // IO可讀可寫 
ev_stat // 檔案屬性變化 
ev_signal // 信號處理 
ev_timer // 相對計時器 
ev_periodic // 絕對計時器 
ev_child // 子進程狀態變化 
ev_fork // fork事件 
ev_cleanup // event loop退出觸發事件 
ev_idle // event loop空閒觸發事件 
ev_embed // 嵌入另一個後臺迴圈 
ev_prepare // event loop之前事件 
ev_check // event loop之後事件 
ev_async // 執行緒間非同步事件

Sample

/*
 * libev_sample.c
 */

#include <stdio.h>
#include <time.h>
#include <ev.h>

// stop timer at counter == 10
#define STOP 10

void showNowTime();

int counter = 0;

void timeout_cb(struct ev_loop *loop, struct ev_timer *w, int revents){
    printf("timeout_cb at ");
    showNowTime();
    
    counter ++;

    if(counter == STOP) 
        
ev_timer_stop(loop, w);
}

int main(){
  
 // use the default event loop
    struct ev_loop *loop = ev_default_loop(0);
    
    
ev_timer timeout_watcher;
    
 
   // initialize an timer watcher
    // the event will occur after 3 sec, and repeat every 1 sec.

    ev_timer_init(&timeout_watcher, timeout_cb, 3, 1);
    
// insert watcher to event loop
    ev_timer_start(loop, &timeout_watcher);
    
  
 // start event loop
    printf("Start loop at ");
    showNowTime();
    
ev_run(loop, 0);
    
    printf("End loop\n");
    return 0;
}

void showNowTime(){
    
time_t now;
    char tbuffer[26];
    
struct tm* tm_info;
    
    
// get total second from 1970/01/01
    time(&now);
    
// convert time_t to struct tm
    tm_info = localtime(&now);
    
// convert struct tm to string assigned
    strftime(tbuffer, sizeof(tbuffer), "%Y/%m/%d %H:%M:%S", tm_info);
    
    printf("%s\n", tbuffer);
}

執行結果

安裝libevent

1.下載libevent

wget http://dist.schmorp.de/libev/libev-4.22.tar.gz

2.解壓縮

chmod 777 libev-4.22.tar.gz 

tar -xvf libev-4.11.tar.gz

3.配置與安裝

./configure

make

sudo make install

4.設定環境變數

export LD_LIBRARY_PATH=/usr/local/lib

5.編譯翻譯程式

gcc -o timer_sample timer_sample.c -lev

./timer_sample


參考資料

 

http://c4fun.cn/blog/2014/03/06/libev-study/

https://www.ibm.com/developerworks/cn/aix/library/au-libev/

https://cnodejs.org/topic/4f16442ccae1f4aa270010a3

arrow
arrow
    全站熱搜

    忽倫 發表在 痞客邦 留言(0) 人氣()