-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c
68 lines (53 loc) · 1.2 KB
/
file.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
#include "file.h"
#include "common.h"
int file_open(file_t* f, const char* filename, size_t size) {
int exists = access(filename, F_OK) == 0;
errno = 0;
f->fd = open(filename, O_RDWR | O_CREAT, (mode_t)0600);
if (f->fd < 0) {
rcl_perror("open file_t");
return -1;
}
if (!exists) {
if (ftruncate(f->fd, (off_t)size) != 0) {
rcl_perror("ftruncate file_t");
return -1;
}
}
f->bytes = size;
f->locked = false;
int flags = PROT_READ | PROT_WRITE;
#ifdef MAP_HUGETLB
flags = flags | MAP_HUGETLB;
#endif
f->buffer = mmap(NULL, f->bytes, flags, MAP_SHARED, f->fd, 0);
if (f->buffer == MAP_FAILED) {
rcl_perror("mmap file_t");
return -1;
}
return 0;
}
int file_lock(file_t* f) {
if (f->locked)
return 0;
f->locked = true;
return mlock(f->buffer, f->bytes) == 0 ? 0 : -1;
}
int file_unlock(file_t* f) {
if (!f->locked)
return 0;
return munlock(f->buffer, f->bytes) == 0 ? 0 : -1;
}
/*
int file_resize(file_t* f, size_t size) {
if (size > RCL_FILE_SIZE_RESERVE) {
return -1;
}
f->bytes = size;
return ftruncate(f->fd, size) == 0 ? 0 : -1;
}
*/
int file_close(file_t* f) {
munmap(f->buffer, f->bytes);
return close(f->fd);
}