-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmem.c
58 lines (52 loc) · 1.18 KB
/
mem.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
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "mem.h"
void *mmap_alloc(size_t len)
{
int fd;
int result;
int protection = PROT_READ | PROT_WRITE;
int visibility = MAP_ANONYMOUS | MAP_SHARED;
void *addr;
fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0666);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
result = lseek(fd, len - 1, SEEK_SET);
if (result == -1) {
perror("lseek");
exit(EXIT_FAILURE);
}
write(fd, "", 1);
addr = mmap(NULL, len, protection, visibility, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
close(fd);
memset(addr, 0, len);
return addr;
}
void mmap_free(void *addr)
{
int fd;
struct stat sb;
fd = open(FILEPATH, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
if (fstat(fd, &sb) == -1 || !S_ISREG (sb.st_mode)) {
perror("fstat");
exit(EXIT_FAILURE);
}
memset(addr, 0, sb.st_size);
munmap(addr, sb.st_size);
close(fd);
}