| 1 | #include <new>
|
|---|
| 2 | #include <cstdio>
|
|---|
| 3 | #include <cstdlib>
|
|---|
| 4 |
|
|---|
| 5 | #include <iostream>
|
|---|
| 6 |
|
|---|
| 7 | #include <memory>
|
|---|
| 8 | #include <string>
|
|---|
| 9 | #include <boost/interprocess/sync/mutex_family.hpp>
|
|---|
| 10 | #include <boost/interprocess/indexes/null_index.hpp>
|
|---|
| 11 | #include <boost/interprocess/managed_mapped_file.hpp>
|
|---|
| 12 |
|
|---|
| 13 | class Test
|
|---|
| 14 | {
|
|---|
| 15 | public:
|
|---|
| 16 | Test *test;
|
|---|
| 17 | };
|
|---|
| 18 |
|
|---|
| 19 | typedef boost::interprocess::basic_managed_mapped_file <
|
|---|
| 20 | char,
|
|---|
| 21 | boost::interprocess::rbtree_best_fit <
|
|---|
| 22 | boost::interprocess::null_mutex_family,
|
|---|
| 23 | boost::interprocess::offset_ptr<void>
|
|---|
| 24 | >,
|
|---|
| 25 | boost::interprocess::null_index
|
|---|
| 26 | > memory_mapped_file;
|
|---|
| 27 |
|
|---|
| 28 | void* operator new(size_t size, memory_mapped_file &a)
|
|---|
| 29 | {
|
|---|
| 30 | return a.allocate(size);
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | int main()
|
|---|
| 34 | {
|
|---|
| 35 | using namespace boost::interprocess;
|
|---|
| 36 | //Remove shared memory on construction and destruction
|
|---|
| 37 | struct shm_remove
|
|---|
| 38 | {
|
|---|
| 39 | shm_remove() { std::remove("MySharedMemory"); }
|
|---|
| 40 | ~shm_remove(){ std::remove("MySharedMemory"); }
|
|---|
| 41 | } remover;
|
|---|
| 42 |
|
|---|
| 43 | Test *p;
|
|---|
| 44 |
|
|---|
| 45 | {
|
|---|
| 46 | //Create a managed shared memory
|
|---|
| 47 | memory_mapped_file shm(create_only, "MySharedMemory", 10000);
|
|---|
| 48 |
|
|---|
| 49 | //Check size
|
|---|
| 50 | std::cout << shm.get_size() << '\n';
|
|---|
| 51 | p = new(shm) Test();
|
|---|
| 52 | p->test = new(shm) Test();
|
|---|
| 53 |
|
|---|
| 54 | //Check pointers
|
|---|
| 55 | std::cout << "before growing:" << '\n';
|
|---|
| 56 | std::cout << "size: " << shm.get_size() << '\n';
|
|---|
| 57 | std::cout << "p is owned: " << shm.belongs_to_segment(p) << '\n';
|
|---|
| 58 | std::cout << "p->test is owned: " << shm.belongs_to_segment(p->test) << '\n';
|
|---|
| 59 | std::cout << "p->test = " << p->test << '\n';
|
|---|
| 60 | }
|
|---|
| 61 | {
|
|---|
| 62 | //Now that the segment is not mapped grow it adding extra 500 bytes
|
|---|
| 63 | memory_mapped_file::grow("MySharedMemory", 7*500);
|
|---|
| 64 |
|
|---|
| 65 | //Map it again
|
|---|
| 66 | memory_mapped_file shm(open_only, "MySharedMemory");
|
|---|
| 67 | //Check pointers
|
|---|
| 68 | std::cout << "after growing" << '\n';
|
|---|
| 69 | std::cout << "size: " << shm.get_size() << '\n';
|
|---|
| 70 | std::cout << "p is owned: " << shm.belongs_to_segment(p) << '\n';
|
|---|
| 71 | std::cout << "p->test is owned: " << shm.belongs_to_segment(p->test) << '\n';
|
|---|
| 72 | std::cout << "p->test = " << p->test << '\n';
|
|---|
| 73 | }
|
|---|
| 74 | return 0;
|
|---|
| 75 | }
|
|---|