open() not working with O_DIRECT flag on UBUNTU

c++, disk, file-io, linux, ubuntu

Solution

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`.

Problem

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; } ```

Original source

Related problems