#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <liburing.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
struct io_uring ring;
if (io_uring_queue_init(8, &ring, 0) != 0) {
perror("io_uring_queue_init");
return 1;
}
int fd = open(argv[1], O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("open");
return 1;
}
char *buffer = malloc(BUFFER_SIZE);
if (!buffer) {
perror("malloc");
return 1;
}
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
if (!sqe) {
fprintf(stderr, "No space for a new SQE\n");
return 1;
}
io_uring_prep_read(sqe, fd, buffer, BUFFER_SIZE, 0);
io_uring_sqe_set_data(sqe, buffer);
int submit_ret = io_uring_submit(&ring);
if (submit_ret != 1) {
fprintf(stderr, "io_uring_submit: %d\n", submit_ret);
return 1;
}
struct io_uring_cqe *cqe;
unsigned head = 0;
for (;;) {
io_uring_wait_cqe(&ring, &cqe);
if (cqe->res != BUFFER_SIZE) {
fprintf(stderr, "Read failed: %ld\n", cqe->res);
return 1;
}
char *buffer = (char *)io_uring_cqe_get_data(cqe);
printf("Read: %s\n", buffer);
free(buffer);
io_uring_cq_advance(&ring, head);
head++;
// 重新提交读取操作
sqe = io_uring_get_sqe(&ring);
if (!sqe) {
fprintf(stderr, "No space for a new SQE\n");
return 1;
}
buffer = malloc(BUFFER_SIZE);
if (!buffer) {
perror("malloc");
return 1;
}
io_uring_prep_read(sqe, fd, buffer, BUFFER_SIZE, 0);
io_uring_sqe_set_data(sqe, buffer);
submit_ret = io_uring_submit(&ring);
if (submit_ret != 1) {
fprintf(stderr, "io_uring_submit: %d\n", submit_ret);
return 1;
}
// 退出循环条件:读取到文件末尾或发生错误
if (cqe->res == 0) {
break;
}
}
close(fd);
io_uring_queue_exit(&ring)
评论已关闭