From 65b17173bda92a5e03f931244eca3f8afa127328 Mon Sep 17 00:00:00 2001 From: Martin Pärtel Date: Sun, 28 Apr 2019 23:36:32 +0300 Subject: Cleanups, tests and optimizations for #74. --- tests/odirect_read.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 tests/odirect_read.c (limited to 'tests/odirect_read.c') diff --git a/tests/odirect_read.c b/tests/odirect_read.c new file mode 100644 index 0000000..8fc746b --- /dev/null +++ b/tests/odirect_read.c @@ -0,0 +1,59 @@ +#ifdef __linux__ + +#include + +#include +#include +#include +#include +#include + +#ifndef O_DIRECT +#define O_DIRECT 00040000 /* direct disk access hint */ +#endif + +int main(int argc, char** argv) { + if (argc != 2) { + fprintf(stderr, "Expected 1 argument: the file to read.\n"); + return 1; + } + + int fd = open(argv[1], O_RDONLY | O_DIRECT); + if (fd == -1) { + perror("failed to open file"); + return 1; + } + + const size_t buf_size = 4096; + unsigned char* buf = mmap(NULL, buf_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); + if (buf == MAP_FAILED) { + perror("mmap failed"); + return 1; + } + + while (1) { + ssize_t amt_read = read(fd, buf, buf_size); + if (amt_read == 0) { + break; + } + if (amt_read == -1) { + perror("failed to read file"); + return 1; + } + fwrite(buf, 1, amt_read, stdout); + fflush(stdout); + } + + return 0; +} + +#else // __linux__ + +#include + +int main() { + fprintf(stderr, "Not supported on this platform.\n"); + return 1; +} + +#endif // __linux__ -- cgit v1.2.3