shm implemented as memfd syscall
zhangmeng
2023-07-27 157b3411dd123694ca29dd80fe9ecc683958ccab
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
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "memfd.h"
 
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
 
int main(int argc, char *argv[])
{
  int fd;
  char *name;
  ssize_t i, len;
  unsigned char* paddr;
  struct stat st;
  int ret = 0;
 
  if (argc < 3) {
    fprintf(stderr, "%s name size\n", argv[0]);
    exit(EXIT_FAILURE);
  }
 
  name = argv[1];
  len = atoi(argv[2]) * 1024LU * 1024LU * 1024LU;
 
  /* Create an anonymous file in tmpfs; */
 
  fd = basic_shm_create(name, len);
 
  if (fd == -1)
    errExit("memfd_create");
 
  /* Size the file as specified on the command line */
 
  ret =  basic_shm_mmap (fd, &paddr);
  if (ret < 0)
    errExit("basic_shm_mmap");
 
  for (i = 0; i < len; ++i)
    paddr[i] = i & 0x000000FF;
 
  if (fstat (fd, &st))
    errExit ("fstat");
 
  printf("length: %zu, atime: %lu.%lu\n", len, st.st_atim.tv_sec, st.st_atim.tv_nsec);
  fprintf(stderr, "pid:%d,fd:%d\n", getpid(), fd);
 
  /* Keep running, so that the file created by memfd_create()
     continues to exist */
 
 
  sleep (120);
  //pause();
 
  printf("length: %zu, atime: %lu.%lu\n", len, st.st_atim.tv_sec, st.st_atim.tv_nsec);
  ret =  basic_shm_unmmap(fd, &paddr);
  if (ret < 0)
    errExit("basic_shm_unmmap");
 
 
  /*open to test again*/
  fd = basic_shm_open(fd, 0, 0);
  if (fd <= 0)
    errExit("basic_shm_open");
 
  ret =  basic_shm_mmap (fd, &paddr);
  if (ret < 0)
    errExit("basic_shm_mmap");
 
  printf ("start: ");
  for (i = 0; i < 32; ++i)
    printf ("%i ", paddr[i]);
  printf ("\nend: ");
  for (i = 0; i < 32; ++i)
    printf ("%i ", paddr[len-32+i]);
  printf ("\ndone\n");
 
  ret =  basic_shm_unmmap(fd, &paddr);
  if (ret < 0)
    errExit("basic_shm_unmmap");
    
  basic_shm_close(fd);
 
  exit(EXIT_SUCCESS);
}