HOG2
MMapUtil.cpp
Go to the documentation of this file.
1 //
2 // MMapUtil.c
3 // hog2 glut
4 //
5 // Created by Nathan Sturtevant on 10/14/13.
6 // Copyright (c) 2013 University of Denver. All rights reserved.
7 //
8 
9 #include <stdio.h>
10 #include <assert.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <stdint.h>
14 #include <unistd.h>
15 #include <sys/mman.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <cinttypes>
20 
21 #ifndef MAP_ANONYMOUS
22 #define MAP_ANONYMOUS MAP_ANON
23 #endif
24 
25 #define handle_error(msg) \
26 do { perror(msg); exit(EXIT_FAILURE); } while (0)
27 
28 uint8_t *GetMMAP(const char *filename, uint64_t mapSize, int &fd, bool zero)
29 {
30  uint8_t *memblock;
31 
32  if (filename == 0)
33  {
34  memblock = (uint8_t *)mmap(NULL, mapSize, PROT_WRITE|PROT_READ, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
35  if (memblock == MAP_FAILED)
36  {
37  handle_error("mmap");
38  }
39  return memblock;
40  }
41 
42  //int fd;
43  struct stat sb;
44 
45  printf("Size of off_t is (%lu), uint64_t is (%lu)\n", sizeof(off_t), sizeof(uint64_t));
46  if (zero)
47  {
48  if ((fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1)
49  {
50  handle_error("open");
51  }
52  if (lseek(fd, mapSize-1, SEEK_SET) == -1)
53  {
54  handle_error("lseek");
55  }
56  if (write(fd, "", 1) != 1)
57  {
58  handle_error("write");
59  }
60 
61  fstat(fd, &sb);
62  printf("Size: %" PRId64 " \n",(uint64_t)sb.st_size);
63  assert(sb.st_size == mapSize);
64  }
65  else {
66  if ((fd = open(filename, O_RDWR, 0666)) == -1)
67  {
68  handle_error("open");
69  }
70  }
71 
72  fstat(fd, &sb);
73  printf("Size: %" PRId64 " \n",(uint64_t)sb.st_size);
74  assert(sb.st_size >= mapSize);
75 
76  memblock = (uint8_t *)mmap(NULL, sb.st_size, PROT_WRITE|PROT_READ, /*MAP_PRIVATE|MAP_POPULATE*/MAP_SHARED, fd, 0);
77  //madvise(memblock, sb.st_size, MADV_RANDOM|MADV_WILLNEED);
78  if (memblock == MAP_FAILED)
79  {
80  handle_error("mmap");
81  }
82  return memblock;
83 }
84 
85 void CloseMMap(uint8_t *mem, uint64_t mapSizeBytes, int fd)
86 {
87  if (munmap(mem, mapSizeBytes) != 0)
88  {
89  handle_error("unmap");
90  }
91  if (close(fd) == -1)
92  {
93  handle_error("close");
94  }
95 }
CloseMMap
void CloseMMap(uint8_t *mem, uint64_t mapSizeBytes, int fd)
Definition: MMapUtil.cpp:85
MAP_ANONYMOUS
#define MAP_ANONYMOUS
Definition: MMapUtil.cpp:22
handle_error
#define handle_error(msg)
Definition: MMapUtil.cpp:25
GetMMAP
uint8_t * GetMMAP(const char *filename, uint64_t mapSize, int &fd, bool zero)
Definition: MMapUtil.cpp:28