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

Eri*_*ang 2 c linux io

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

顺便说一下,我知道直接io通常应该与程序级缓存一起使用,下面的程序只是想对直接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;
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*thy 5

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