#define _GNU_SOURCE #include #include #include #include #include #include #include #include #define T_TEST_TEXT "This is a test\n" #define BUF_SIZE 32 /* 16 won't work, 17 will cause segfault */ //#define READ_SIZE 16 #define READ_SIZE 17 int test_write(char *testfile) { int fd; int ret; int status; char buf[BUF_SIZE]; status = 0; printf("Write file with O_DIRECT\n"); memset(buf, 'a', BUF_SIZE); /* Buffered write or direct write both work */ fd = open(testfile, O_CREAT | O_RDWR | O_DIRECT | O_TRUNC, 0644); // fd = open(testfile, O_CREAT | O_RDWR | O_TRUNC, 0644); if (fd == -1) { printf("FAIL - open: %s\n", strerror(errno)); exit(EXIT_FAILURE); } ret = write(fd, T_TEST_TEXT, sizeof(T_TEST_TEXT)); if (ret == -1) { printf("FAIL - write: %s\n", strerror(errno)); exit(EXIT_FAILURE); } close(fd); printf("Read file with O_DIRECT\n"); /* Only direct read would get segfault */ fd = open(testfile, O_RDONLY | O_DIRECT); // fd = open(testfile, O_RDONLY); ret = read(fd, buf, READ_SIZE); if (ret == -1) { printf("FAIL - re-read: %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (!strcmp(buf, T_TEST_TEXT)) { printf("PASS\n"); } else { printf("FAIL - expect \"%s\" - got \"%s\"\n", T_TEST_TEXT, buf); status++; } close(fd); return status; } int main(int argc, char *argv[]) { int ret; ret = test_write(argv[1]); exit(ret); }