题目
[TOC]
1. 采用libevent库,编写一个间隔几秒钟打印一遍程序的程序。
参考答案:
#include<event.h>
#include <stdio.h>
/*
编译命令 gcc 文件 -levent
*/
void func_cb(evutil_socket_t fd, short flag, void* div_arg)
{
struct timeval* tv = div_arg;
struct timeval cur_tv;
evutil_gettimeofday(&cur_tv, NULL);
evutil_timersub(&cur_tv, tv, &cur_tv);
double elapsed = cur_tv.tv_sec * 1000 + cur_tv.tv_usec/1000;
printf("hello world! ");
printf("elapsed %f\n", elapsed);
}
int main(int argc ,char* argv)
{
struct event ev;
struct event_base* base;
struct timeval tv;
struct timeval interval;
base = event_base_new();
evutil_gettimeofday(&tv, NULL);
//EV_PERSIST
event_assign(&ev, base, -1, 0, func_cb, &tv);
evutil_timerclear(&interval);
interval.tv_sec = 1;
event_add(&ev, &interval);
event_base_dispatch(base);
return 0;
}
网友评论