Write a file using O_DIRECT flag

I had a requirement to write a file using O_DIRECT flag. This flag is passed while opening a file so that whatever read/write happens on that file desc, will not use the page cache and will go directly to the block layer device.

The requirements of using O_DIRECT flag are:
1) Need aligned (of block/sector size) size for read/write
2) Need aligned (of block/sector size) buffer allocated to read/write

Following is the code to do that.

#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <malloc.h>
#include <string.h>

#define SIZE (512*32)
int main(int argc, char *argv[])
{
        char *x;
        int count = 0, ret;
        int fd = open(argv[1], O_RDWR | O_CREAT | O_DIRECT);
        if (fd > 0) {
                ret = posix_memalign(&x, SIZE, SIZE);
                if (ret < 0) {
                        close(fd);
                        return -1;
                }
                memset(x, atoi(argv[2]), SIZE);
                while (write(fd, x, SIZE) > 0) {
                    //do nothing till the volume is filled;
                }
                free(x);
                close(fd);
        }
        return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s