gpt4 book ai didi

c++ - 使用带有 O_DIRECT 标志的 libaio 读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:45 24 4
gpt4 key购买 nike

我正在使用异步 lib​​aio 读取文件。下面的代码显示了我是如何做到的。代码工作正常,但现在我想切换到 O_DIRECT 模式以避免文件缓存。当我将第 25 行更改为 fd = open("./testfile", O_RDONLY|O_DIRECT);程序停止正常工作。 (io_getevents 不返回任何数据)。你能帮我调整程序,使其在 O_DIRECT 标志下也能正常工作吗?

提前致谢

操作系统:Ubuntu 12.10 3.5.0-26-generic)

1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <sys/param.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 #include <libaio.h>
10
11 int main(int argc, char* argv[]) {
12
13 struct iocb cb;
14 struct iocb* iocbs = &cb;
15 struct io_event events[1];
16 char data[4096];
17 io_context_t ctx;
18 int fd;
19 int res;
20
21 memset(&ctx, 0, sizeof(ctx));
22 memset(&cb, 0, sizeof(cb));
23 memset(&data, 0, sizeof(data));
24
25 fd = open("./testfile", O_RDONLY);
26
27 if(io_setup(1, &ctx) < 0) {
28 printf("io_setup error\n");
29 exit(-1);
30 }
31 printf("io_setup OK\n");
32
33 // submit read request
34 io_prep_pread(&cb, fd, &data, 1024, 0);
35 res = io_submit(ctx, 1, &iocbs);
36 if(res < 0) {
37 printf("io_submit error\n");
38 exit(-2);
39 }
40 printf("io_submit OK: %d\n", res);
41
42 // get events
43 res = io_getevents(ctx, 0, 1, events, NULL);
44 if(res < 0) {
44 if(res < 0) {
45 printf("io_getevents Error: %d", res);
46 exit(-3);
47 }
48 printf("io_getevents OK: %d %li %li\n", res, events[0].res, events[0].res2);
49
50 // dump data received
51 char data_prefix[16];
52 strncpy(data_prefix, data, 15);
53 data_prefix[15] = 0;
54 printf("data: %s\n", data_prefix);
55
56 res = io_destroy(ctx);
57 if(res < 0) {
58 printf("io_destroy Error: %d\n", res);
59 exit(-4);
60 }
61 printf("io_destroy OK: %d\n", res);
62
63 res = close(fd);
64 printf("close: %d\n", res);
65 }

最佳答案

您需要将缓冲区对齐到 512 字节,O_DIRECT 才能正常工作。在 io_prep_pread 之前:

char *data;
posix_memalign(&data, 512, 1024);

请注意,读取的大小必须是 512 的倍数。

关于c++ - 使用带有 O_DIRECT 标志的 libaio 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com