gpt4 book ai didi

c - 直接 io - O_DIRECT 在写入文件时似乎不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:13:36 49 4
gpt4 key购买 nike

在 Linux 上(Linux 3.16.0-38-generic#52~14.04.1-Ubuntu x86_64 GNU/Linux),当尝试使用 O_DIRECT 通过直接 io 写入文件时 flag enabled,写入后好像文件还是空的,求助。

顺便说一句,我知道direct io通常应该与程序级缓存一起使用,下面的程序只是想在direct io上进行测试。

direct_io_test.c:

// direct io test

#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int direct_io_test() {
char *fp= "/tmp/direct_io.txt";
int flag = O_RDWR | O_CREAT | O_APPEND | O_DIRECT;
mode_t mode = 0644;

int fd = open(fp, flag, mode);
if (fd == -1) {
printf("Failed to open file. Error: \t%s\n", strerror(errno));
return errno;
} else {
printf("Succeed to open file, file descriptor: %d\n", fd);
}

// TODO ... seems didn't write to file,
write(fd, "hello\n", 6);

close(fd);
return 0;
}

int main(int argc, char *argv[]) {
direct_io_test();

return 0;
}

最佳答案

检查写入的返回值。您从中复制的字符串文字可能未在内存中正确对齐 O_DIRECT,因此写入调用可能会失败。

关于c - 直接 io - O_DIRECT 在写入文件时似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578637/

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