2

On linux (Linux 3.16.0-38-generic #52~14.04.1-Ubuntu x86_64 GNU/Linux), When try to write to a file via direct io with O_DIRECT flag enabled, it seems after write, the file is still empty, please help.

By the way, I am aware of direct io should normally be used with program level cache, following program just want to have a test on 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;
}
Eric
  • 22,183
  • 20
  • 145
  • 196

1 Answers1

5

Check the return value from write. The string literal you copy from is probably not properly aligned in memory for O_DIRECT, so the write call probably fails.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
  • 1
    Yes, the `write()` failed with `Invalid argument`, probably due to didn't met the memory align required by `O_DIRECT`. It seems should not copy literal string for `O_DIRECT`. – Eric Nov 07 '15 at 06:13
  • @EricWang Can you explain in depth what the problem was and how you solved it? I am facing similar issues. Thank you.. – Kadam Parikh Apr 16 '20 at 06:52
  • @KadamParikh I was just testing `O_DIRECT` when asking the question, and didn't solve the issue, you may try to check this post: https://stackoverflow.com/questions/34182535 , basically the buffer need to be aligned to disk file block and os page. – Eric Apr 18 '20 at 06:54
  • the buffer must be aligned **and** the write size must be dividable by a block size which is supported by your device. – maxschlepzig Aug 15 '21 at 12:59