mincore: add '-s' summary option
[pcu.git] / fadvise.c
blob12c9b1b75cab5971a9ce772408b7160251388ab2
1 #include "compat-util.h"
3 static struct fa_advice {
4 const char *name;
5 const int nr;
6 } advice_table[] = {
7 { "normal", POSIX_FADV_NORMAL },
8 { "sequential", POSIX_FADV_SEQUENTIAL },
9 { "random", POSIX_FADV_RANDOM },
10 { "noreuse", POSIX_FADV_NOREUSE },
11 { "willneed", POSIX_FADV_WILLNEED },
12 { "dontneed" , POSIX_FADV_DONTNEED }
15 static int usage(const char * argv0)
17 int i;
19 fprintf(stderr,
20 "Usage: %s [-a ADVICE] [-o OFFSET] "
21 "[-l LENGTH] FILE...\n", argv0);
22 fprintf(stderr, "\nPossible values for advice:\n");
23 for (i = 0; i < ARRAY_SIZE(advice_table); ++i)
24 fprintf(stderr, "\t%s\n", advice_table[i].name);
26 return 1;
29 static void apply_fadvise(const char *path, off_t offset, off_t len, int advice)
31 int fd;
33 if ((fd = open(path, O_RDONLY|O_NOATIME)) < 0) {
34 fprintf(stderr, "%s: open(): %s\n", path, strerror(errno));
35 return;
38 if (len <= 0) {
39 /* for compatibility with kernels < 2.6.6 */
40 struct stat sb;
42 if (fstat(fd, &sb) < 0) {
43 fprintf(stderr, "%s: fstat(%d): %s\n",
44 path, fd, strerror(errno));
45 goto out;
47 len = sb.st_size;
50 if (posix_fadvise(fd, offset, len, advice) < 0)
51 fprintf(stderr,
52 "%s: posix_fadvise("
53 "offset=%lu,len=%lu,advice=%d): %s\n",
54 path,
55 (unsigned long)offset,
56 (unsigned long)len,
57 advice, strerror(errno));
59 out:
60 close(fd);
63 int main(int argc, char * const argv[])
65 off_t offset = 0;
66 off_t len = 0;
67 int advice = POSIX_FADV_NORMAL;
68 int opt;
69 int argi = 1;
71 while ((opt = getopt(argc, argv, "o:l:a:h")) != -1) {
72 int i;
73 char *err;
75 argi += 2;
76 switch(opt) {
77 case 'o':
78 offset = cstr_to_off_t(optarg, &err, 10);
79 if (*err || offset < 0) {
80 fprintf(stderr, "offset must be >= 0\n");
81 return 1;
83 break;
84 case 'l':
85 len = cstr_to_off_t(optarg, &err, 10);
86 if (*err || len < 0) {
87 fprintf(stderr, "length must be >= 0\n");
88 return 1;
90 break;
91 case 'a':
92 for (i = 0; i < ARRAY_SIZE(advice_table); ++i) {
93 if (strcmp(advice_table[i].name, optarg))
94 continue;
95 advice = advice_table[i].nr;
96 break;
98 if (i < ARRAY_SIZE(advice_table))
99 break;
100 fprintf(stderr, "advice '%s' not understood\n", optarg);
101 /* fall-through */
102 default:
103 return usage(argv[0]);
107 if (argi >= argc)
108 return usage(argv[0]);
110 for (; argi < argc; ++argi)
111 apply_fadvise(argv[argi], offset, len, advice);
112 return 0;