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
| #include "memfd_shm.h"
|
| #include <stdio.h>
| #include <sys/types.h>
| #include <sys/stat.h>
| #include <unistd.h>
| #include <sys/mman.h>
| #include <sys/syscall.h>
| #include <errno.h>
| #include <fcntl.h>
| #include <linux/memfd.h>
| #include <stdlib.h>
|
| static inline int sys_memfd_create(const char *name,
| unsigned int flags)
| {
| return syscall(__NR_memfd_create, name, flags);
| }
|
| int basic_shm_create(const char *name, int len){
| int fd;
| struct stat st;
|
| /* Create an anonymous file in tmpfs; */
| if(0 >= len)
| {
| return -1;
| }
|
| fd = sys_memfd_create(name, MFD_CLOEXEC);
|
| if (fd == -1)
| {
| return -1;
| }
|
| /* Size the file as specified on the command line */
|
| if (ftruncate(fd, len) == -1)
| {
| close(fd);
| return -1;
| }
|
| if (fstat (fd, &st))
| {
| close(fd);
| return -1;
| }
|
| // printf("PID: %ld; fd: %d; /proc/%ld/fd/%d, atime: %lu.%lu\n",
| // (long) getpid(), fd, (long) getpid(), fd, st.st_atim.tv_sec, st.st_atim.tv_nsec);
|
| return fd;
| }
|
| int basic_shm_mmap(int fd, unsigned char** ppaddr){
| struct stat st;
| ssize_t len;
| if (fstat (fd, &st))
| {
| return -1;
| }
| len = st.st_size;
|
| *ppaddr = (unsigned char*) mmap (NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
| if (*ppaddr == MAP_FAILED)
| {
| return -1;
| }
|
| // printf("length: %zu, atime: %lu.%lu\n", len, st.st_atim.tv_sec, st.st_atim.tv_nsec);
| return len;
| }
|
| int basic_shm_unmmap(int fd, unsigned char** ppaddr){
| struct stat st;
| ssize_t len;
| int ret = 0;
| if (fstat (fd, &st))
| {
| return -1;
| }
| len = st.st_size;
|
| ret = munmap((void *)*ppaddr, len);
| if (ret == -1)
| {
| return -1;
| }
| *ppaddr = NULL;
| // printf("length: %zu, atime: %lu.%lu\n", len, st.st_atim.tv_sec, st.st_atim.tv_nsec);
| return len;
| }
|
| int basic_shm_close(int fd){
| int ret = -1;
| if (fd >= 0)
| {
| ret = close(fd);
| }
| return ret;
| }
|
|