-
Notifications
You must be signed in to change notification settings - Fork 0
/
duncache.c
92 lines (76 loc) · 2.01 KB
/
duncache.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>
#include <string.h>
#include <errno.h>
/*
* duncache.c
* Remove files/directories from the Linux page cache with POSIX_FADV_DONTNEED and fts().
* http://github.com/jrelo/duncache
*/
void duncache_file(const char *filepath);
void duncache_directory(const char *dirpath);
int compare(const FTSENT **, const FTSENT **);
int main(int argc, char *const argv[]) {
if (argc < 2) {
printf("Usage: %s <path>\n", argv[0]);
exit(255);
}
for (int i = 1; i < argc; i++) {
struct stat sb;
if (stat(argv[i], &sb) == 0 && S_ISDIR(sb.st_mode)) {
duncache_directory(argv[i]);
} else {
duncache_file(argv[i]);
}
}
return 0;
}
void duncache_file(const char *filepath) {
int fd = open(filepath, O_RDONLY);
if (fd == -1) {
perror("open");
return;
}
if (fdatasync(fd) == -1) {
perror("fdatasync");
close(fd);
return;
}
if (posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED) == -1) {
perror("posix_fadvise");
close(fd);
return;
}
printf("%s -> POSIX_FADV_DONTNEED\n", filepath);
close(fd);
}
void duncache_directory(const char *dirpath) {
char *paths[] = {(char *)dirpath, NULL};
FTS *fs = fts_open(paths, FTS_COMFOLLOW | FTS_NOCHDIR, &compare);
if (NULL == fs) {
perror("fts_open");
return;
}
FTSENT *child = NULL;
FTSENT *parent = NULL;
while ((parent = fts_read(fs)) != NULL) {
child = fts_children(fs, 0);
if (errno != 0) {
perror("fts_children");
}
while ((NULL != child)) {
duncache_file(child->fts_accpath);
child = child->fts_link;
}
}
fts_close(fs);
}
int compare(const FTSENT **one, const FTSENT **two) {
return (strcmp((*one)->fts_name, (*two)->fts_name));
}