-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmem_3.c
More file actions
85 lines (68 loc) · 1.95 KB
/
Copy pathmem_3.c
File metadata and controls
85 lines (68 loc) · 1.95 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
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ftw.h>
#include <unistd.h>
#include <sys/mman.h>
#include "memlayout.h"
/**
* Loading a large data file onto memory via mmap()
* @param path
*/
void mem_loading(const char* path);
/**
* In this example, mmap() a large data file and observe the memory changing. Project includes a
* 300KB json data file as an example. If no argument is provided, the file is default to Tags.json
* @author: Danh Nguyen
* @return
*/
int main(int argc, char *argv[]) {
const char* path;
if (argc > 2) {
printf("Too many arguments!\n");
exit(-1);
}
if (argc == 2)
path = argv[1];
else
path = "Tags.json\0";
unsigned int array_size = 20;
struct memregion* before = (struct memregion*)malloc(array_size * sizeof(struct memregion));
struct memregion* after = (struct memregion*)malloc(array_size * sizeof(struct memregion));
printf("\nMemory before mmap():\n");
int status = get_mem_layout(before, array_size);
for (unsigned int i = 0; i < array_size; i++) {
print_memregion(before[i]);
}
printf("\nLoading file \"%s\" to memory\n", path);
mem_loading(path);
get_mem_layout(after, array_size);
for (unsigned int i = 0; i < array_size; i++) {
print_memregion(after[i]);
}
memregion_compare(before, after, array_size);
}
void mem_loading(const char* path) {
struct stat buffer;
int fd = open(path, O_RDONLY);
if (fd < 0) {
printf("Can't open\n");
exit(1);
}
int error = fstat(fd, &buffer);
if (error < 0) {
printf("error");
exit(2);
}
char *ptr = mmap(NULL,buffer.st_size,
PROT_READ,
MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf("Mapping Failed\n");
return;
}
close(fd);
printf("Successfully mapped!\n");
printf("====================\n");
}