-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfd_cache.c
More file actions
109 lines (101 loc) · 2.43 KB
/
fd_cache.c
File metadata and controls
109 lines (101 loc) · 2.43 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
typedef struct {
char *path;
int fd;
int age;
} fd_entry_t;
typedef struct {
fd_entry_t *items;
int cap;
int tick;
} fd_cache_t;
static void fd_cache_init(fd_cache_t *c, int cap)
{
c->items = calloc(cap, sizeof(fd_entry_t));
c->cap = cap;
c->tick = 0;
}
static void fd_cache_close_entry(fd_entry_t *e)
{
if (e->fd >= 0) {
close(e->fd);
e->fd = -1;
}
free(e->path);
e->path = NULL;
e->age = 0;
}
static void fd_cache_destroy(fd_cache_t *c)
{
for (int i = 0; i < c->cap; i++) {
fd_cache_close_entry(&c->items[i]);
}
free(c->items);
}
static int fd_cache_get(fd_cache_t *c, const char *path)
{
c->tick++;
for (int i = 0; i < c->cap; i++) {
if (c->items[i].path && strcmp(c->items[i].path, path) == 0) {
c->items[i].age = c->tick;
return c->items[i].fd;
}
}
int victim = 0;
int oldest = c->tick + 1;
for (int i = 0; i < c->cap; i++) {
if (c->items[i].path == NULL) {
victim = i;
oldest = -1;
break;
}
if (c->items[i].age < oldest) {
oldest = c->items[i].age;
victim = i;
}
}
fd_cache_close_entry(&c->items[victim]);
int fd = open(path, O_RDONLY);
if (fd < 0) return -1;
c->items[victim].path = strdup(path);
c->items[victim].fd = fd;
c->items[victim].age = c->tick;
return fd;
}
static int cached_read_line(fd_cache_t *c, const char *path, char *buf, size_t sz)
{
int fd = fd_cache_get(c, path);
if (fd < 0) return -1;
lseek(fd, 0, SEEK_SET);
ssize_t n = read(fd, buf, sz - 1);
if (n < 0) return -1;
buf[n] = 0;
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s file1 [file2 ...]\n", argv[0]);
return 1;
}
fd_cache_t cache;
fd_cache_init(&cache, 4);
char buf[256];
for (int round = 0; round < 3; round++) {
for (int i = 1; i < argc; i++) {
if (cached_read_line(&cache, argv[i], buf, sizeof buf) == 0) {
printf("[%d] %s: %.*s", round, argv[i], (int)strcspn(buf, "\n") + 1, buf);
} else {
perror("read");
}
}
}
fd_cache_destroy(&cache);
return 0;
}