Merge remote-tracking branch 'origin/fuse_2_9_bugfix'
[fuse.git] / example / fioclient.c
bloba7c0dbe29c66225ababab58547211500878f7f2d
1 /*
2 FUSE fioclient: FUSE ioctl example client
3 Copyright (C) 2008 SUSE Linux Products GmbH
4 Copyright (C) 2008 Tejun Heo <teheo@suse.de>
6 This program can be distributed under the terms of the GNU GPL.
7 See the file COPYING.
8 */
10 /** @file
11 * @tableofcontents
13 * fioclient.c - FUSE fioclient: FUSE ioctl example client
15 * \section section_compile compiling this example
17 * gcc -Wall fioclient.c -o fioclient
19 * \section section_source the complete source
20 * fioclient.c
21 * \include fioclient.c
24 #include <config.h>
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
28 #include <sys/stat.h>
29 #include <sys/ioctl.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <errno.h>
34 #include "fioc.h"
36 const char *usage =
37 "Usage: fioclient FIOC_FILE COMMAND\n"
38 "\n"
39 "COMMANDS\n"
40 " s [SIZE] : get size if SIZE is omitted, set size otherwise\n"
41 " r SIZE [OFF] : read SIZE bytes @ OFF (dfl 0) and output to stdout\n"
42 " w SIZE [OFF] : write SIZE bytes @ OFF (dfl 0) from stdin\n"
43 "\n";
45 static int do_rw(int fd, int is_read, size_t size, off_t offset,
46 size_t *prev_size, size_t *new_size)
48 struct fioc_rw_arg arg = { .offset = offset };
49 ssize_t ret;
51 arg.buf = calloc(1, size);
52 if (!arg.buf) {
53 fprintf(stderr, "failed to allocated %zu bytes\n", size);
54 return -1;
57 if (is_read) {
58 arg.size = size;
59 ret = ioctl(fd, FIOC_READ, &arg);
60 if (ret >= 0)
61 fwrite(arg.buf, 1, ret, stdout);
62 } else {
63 arg.size = fread(arg.buf, 1, size, stdin);
64 fprintf(stderr, "Writing %zu bytes\n", arg.size);
65 ret = ioctl(fd, FIOC_WRITE, &arg);
68 if (ret >= 0) {
69 *prev_size = arg.prev_size;
70 *new_size = arg.new_size;
71 } else
72 perror("ioctl");
74 free(arg.buf);
75 return ret;
78 int main(int argc, char **argv)
80 size_t param[2] = { };
81 size_t size, prev_size = 0, new_size = 0;
82 char cmd;
83 int fd, i, rc;
85 if (argc < 3)
86 goto usage;
88 fd = open(argv[1], O_RDWR);
89 if (fd < 0) {
90 perror("open");
91 return 1;
94 cmd = tolower(argv[2][0]);
95 argc -= 3;
96 argv += 3;
98 for (i = 0; i < argc; i++) {
99 char *endp;
100 param[i] = strtoul(argv[i], &endp, 0);
101 if (endp == argv[i] || *endp != '\0')
102 goto usage;
105 switch (cmd) {
106 case 's':
107 if (!argc) {
108 if (ioctl(fd, FIOC_GET_SIZE, &size)) {
109 perror("ioctl");
110 return 1;
112 printf("%zu\n", size);
113 } else {
114 size = param[0];
115 if (ioctl(fd, FIOC_SET_SIZE, &size)) {
116 perror("ioctl");
117 return 1;
120 return 0;
122 case 'r':
123 case 'w':
124 rc = do_rw(fd, cmd == 'r', param[0], param[1],
125 &prev_size, &new_size);
126 if (rc < 0)
127 return 1;
128 fprintf(stderr, "transferred %d bytes (%zu -> %zu)\n",
129 rc, prev_size, new_size);
130 return 0;
133 usage:
134 fprintf(stderr, "%s", usage);
135 return 1;