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操作。你可以根據自己的需求修改和擴展這些示例代碼。