【问题标题】:direct io - O_DIRECT seems not working when write to file直接 io - 写入文件时 O_DIRECT 似乎不起作用
【发布时间】:2016-02-08 07:10:57
【问题描述】:

在 linux 上(Linux 3.16.0-38-generic #52~14.04.1-Ubuntu x86_64 GNU/Linux),当尝试使用 O_DIRECT 标志通过直接 io 写入文件时启用,好像写完后文件还是空的,请帮忙。

顺便说一下,我知道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
  • 大概在 fcntl.h 中?
  • @MartinJames 是的,来自fcntl.h,需要#define _GNU_SOURCE

标签: c linux io


【解决方案1】:

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

【讨论】:

  • 是的,write()Invalid argument 失败,可能是由于未满足O_DIRECT 要求的内存对齐。似乎不应该为 O_DIRECT 复制文字字符串。
  • @EricWang 您能否深入解释一下问题所在以及您是如何解决的?我面临着类似的问题。谢谢你..
  • @KadamParikh 提问时我只是在测试O_DIRECT,并没有解决问题,您可以尝试查看此帖子:stackoverflow.com/questions/34182535,基本上缓冲区需要对齐磁盘文件块和操作系统页面。
  • 缓冲区必须对齐并且写入大小必须可以被设备支持的块大小整除。
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多