Add a helper: read_once
authorBarret Rhoden <brho@cs.berkeley.edu>
Tue, 22 Sep 2015 15:40:49 +0000 (11:40 -0400)
committerBarret Rhoden <brho@cs.berkeley.edu>
Mon, 28 Sep 2015 19:14:00 +0000 (15:14 -0400)
When dealing with devices, sometimes it's nice to be able to do exactly
one read syscall.

tests/read_once.c [new file with mode: 0644]

diff --git a/tests/read_once.c b/tests/read_once.c
new file mode 100644 (file)
index 0000000..76f5851
--- /dev/null
@@ -0,0 +1,45 @@
+/* Copyright (c) 2015 Google Inc
+ * Barret Rhoden <brho@cs.berkeley.edu>
+ * See LICENSE for details.
+ *
+ * Debugging app: read_once PATH
+ *
+ * opens PATH, does one read syscall, outputs resulting buffer as a string. */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <assert.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+
+#define handle_error(msg) \
+        do { perror(msg); exit(-1); } while (0)
+
+int main(int argc, char *argv[])
+{
+       char *path;
+       int fd, ret;
+       char buf[1024];
+
+       if (argc != 2) {
+               printf("Usage: %s PATH\n", argv[0]);
+               exit(-1);
+       }
+       path = argv[1];
+
+       fd = open(path, O_READ);
+       if (fd < 0)
+               handle_error("Can't open path");
+       ret = read(fd, buf, sizeof(buf));
+       if (ret < 0)
+               handle_error("Can't read");
+       buf[ret] = 0;
+       printf("%s", buf);
+       close(fd);
+       return 0;
+}