5

I'm trying to open a file with the O_DIRECT flag. On Ubuntu, the program fails with errno 22. I just installed Fedora on the same machine with dual boot, and this exact same code runs there smoothly.

I'm running Ubuntu 13.10 with kernel 3.12.6 and g++ of version 4.8.1 and file system ext4. The Fedora I just installed is version 20 with kernel 3.12.6.

#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <errno.h>

using namespace std;

int main(void)
{
    int filedesc = open("testfile.txt", O_RDWR | O_CREAT | O_APPEND | O_DIRECT);
    if (filedesc < 0) {
    std::cout << "fail with errno: " << errno << std::endl;
        return -1;
    }
    return 0;
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
nday
  • 229
  • 1
  • 8

1 Answers1

4

You probably have the data journalling ext4 feature enabled. With data being journalled, writes must be buffered (think about it), so O_DIRECT will fail with EINVAL.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thanks! I'm looking into it. Will report back. – nday Jan 07 '14 at 05:47
  • Thanks you so much, David! You were right. I created a new partition with ext4, turned off journaling for it, and copied the code over there. It now runs. :) – nday Jan 07 '14 at 05:55
  • I have the same problem, but my filesystem is mounted `data=ordered` (default). According to ext4 documentation, O_DIRECT should work. Can anybody confirm my findings? – user1202136 Jul 09 '14 at 14:57
  • Umm, O_DIRECT means the kernel uses DMA to put the results of your I/O requests directly into your user-space buffer. And it has to be aligned for DMA to work. (512 byte on linux, best to use posix_memalign, see http://stackoverflow.com/questions/6563120/what-does-posix-memalign-memalign-do, see also man 2 open - http://man7.org/linux/man-pages/man2/open.2.html ) – PAStheLoD Aug 19 '14 at 16:56