Hi,
I wrote this small piece of code to test the effect of O_DIRECT flag. But for some strange reason the program fails at the write function line with invalid argument. I cant seem to inderstand why it is failing to write. Could anyone please suggest what I am doing wrong.
I am passing a writable file to to at time of invocation.
Thanks.
Code:
#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
void usage(char *command)
{
fprintf(stderr,"usage: %s FILENAME\n", command);
exit(1);
}
int main(int argc, char *argv[])
{
char *filename;
int fd;
char buf[15] = {0};
if(argc != 2) usage(argv[0]);
filename = argv[1];
fd = open(filename, O_CREAT | O_DIRECT | O_RDWR, 0666);
if (fd < 0) {
fprintf(stderr, "ERROR: failed to open `%s': %s \n",
filename, strerror(errno));
exit(1);
}
/* invoke the write system call . Not actually writing anything */
if((write(fd, &buf[0], sizeof(buf[0]) * 15)) == -1) {
fprintf(stderr, "Error writing to file:%s \n", strerror(errno));
close(fd);
exit(1);
}
close(fd);
return 0;
}