Ticket #16622: MMap.cpp

File MMap.cpp, 1.0 KB (added by X512, 3 years ago)

Test program.

Line 
1#include <fcntl.h>
2#include <sys/mman.h>
3#include <stdio.h>
4
5#include <new>
6
7#include <SupportDefs.h>
8
9#include <private/shared/AutoDeleter.h>
10
11
12class Block
13{
14public:
15 Block *next;
16 HandleDeleter<int, int, close> file;
17 void *ptr;
18 size_t size;
19
20 Block(const char *name):
21 file(open(name, O_RDONLY)),
22 ptr(NULL)
23 {
24 if (file.Get() >= 0) {
25 struct stat s;
26 fstat(file.Get(), &s);
27 size = s.st_size;
28 ptr = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, file.Get(), 0);
29 }
30 }
31
32 ~Block()
33 {
34 munmap(ptr, size);
35 ptr = NULL;
36 }
37
38};
39
40
41int main()
42{
43 Block *blocks = NULL;
44 size_t totalSize = 0;
45
46 for (int i = 0; i < 4096; i++) {
47 Block *blk = new(std::nothrow) Block("TestFile");
48 if (blk == NULL || blk->ptr == NULL)
49 break;
50 blk->next = blocks; blocks = blk;
51 totalSize += blk->size;
52 }
53
54 printf("Allocated: %" B_PRIuSIZE, totalSize); getc(stdin);
55
56 while (blocks != NULL) {
57 Block *next = blocks->next;
58 totalSize -= blocks->size;
59 delete blocks;
60 blocks = next;
61 }
62
63 printf("Freed: %" B_PRIuSIZE, totalSize); getc(stdin);
64
65 return 0;
66}