Linux中的libev是一个事件驱动库,用于编写高性能的事件处理程序。以下是一些使用libev的示例代码:
下面是一个简单的libev示例,它创建了一个定时器,每秒触发一次事件:
#include <ev.h>
int main() {
ev_loop *loop;
ev_timer timer;
loop = ev_default_loop(0);
ev_timer_init(&timer, callback, 1.0, 1.0);
ev_timer_start(loop, &timer);
ev_run(loop, 0);
return 0;
}
void callback(struct ev_loop *loop, struct ev_timer *w, int revents) {
printf("Timer triggered!\n");
}
libev也支持信号处理。下面是一个示例,它设置了一个在接收到SIGINT信号时触发的事件:
#include <ev.h>
#include <signal.h>
#include <stdio.h>
void signal_cb(struct ev_loop *loop, struct ev_signal *w, int revents) {
printf("Received SIGINT, exiting...\n");
ev_break(loop, EVBREAK_ALL);
}
int main() {
ev_loop *loop;
ev_signal signal;
loop = ev_default_loop(0);
ev_signal_init(&signal, signal_cb, SIGINT);
ev_signal_start(loop, &signal);
ev_run(loop, 0);
return 0;
}
libev还支持异步I/O操作。下面是一个使用libev实现异步读取文件的示例:
#include <ev.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
void read_cb(struct ev_loop *loop, struct ev_io *w, int revents) {
char buf[1024];
ssize_t n;
n = read(w->fd, buf, sizeof(buf));
if (n > 0) {
buf[n] = '\0';
printf("Read %ld bytes: %s\n", n, buf);
} else if (n == 0) {
printf("End of file\n");
ev_io_stop(loop, w);
} else {
perror("Read error");
ev_io_stop(loop, w);
}
}
int main() {
ev_loop *loop;
ev_io io;
int fd;
loop = ev_default_loop(0);
fd = open("test.txt", O_RDONLY);
if (fd < 0) {
perror("Open error");
return 1;
}
ev_io_init(&io, read_cb, fd, EV_IO_READ);
ev_io_start(loop, &io);
ev_run(loop, 0);
close(fd);
return 0;
}
这些示例展示了libev的一些基本用法,包括定时器、信号处理和异步I/O操作。你可以根据自己的需求修改和扩展这些示例代码。