1 | #include <boost/interprocess/managed_shared_memory.hpp>
|
---|
2 | #include <boost/interprocess/containers/vector.hpp>
|
---|
3 | #include <boost/interprocess/containers/string.hpp>
|
---|
4 | #include <boost/interprocess/allocators/allocator.hpp>
|
---|
5 |
|
---|
6 | int main ()
|
---|
7 | {
|
---|
8 | using namespace boost::interprocess;
|
---|
9 | //Typedefs
|
---|
10 | typedef allocator<char, managed_shared_memory::segment_manager>
|
---|
11 | CharAllocator;
|
---|
12 | typedef basic_string<char, std::char_traits<char>, CharAllocator>
|
---|
13 | MyShmString;
|
---|
14 | typedef allocator<MyShmString, managed_shared_memory::segment_manager>
|
---|
15 | StringAllocator;
|
---|
16 | typedef vector<MyShmString, StringAllocator>
|
---|
17 | MyShmStringVector;
|
---|
18 |
|
---|
19 | //Open shared memory
|
---|
20 | //Remove shared memory on construction and destruction
|
---|
21 | struct shm_remove
|
---|
22 | {
|
---|
23 | shm_remove() { shared_memory_object::remove("MySharedMemory"); }
|
---|
24 | ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
|
---|
25 | } remover;
|
---|
26 |
|
---|
27 | managed_shared_memory shm(create_only, "MySharedMemory", 10000);
|
---|
28 |
|
---|
29 | //Create allocators
|
---|
30 | CharAllocator charallocator (shm.get_segment_manager());
|
---|
31 | StringAllocator stringallocator(shm.get_segment_manager());
|
---|
32 |
|
---|
33 | //This string is in only in this process (the pointer pointing to the
|
---|
34 | //buffer that will hold the text is not in shared memory).
|
---|
35 | //But the buffer that will hold "this is my text" is allocated from
|
---|
36 | //shared memory
|
---|
37 | MyShmString mystring(charallocator);
|
---|
38 | mystring = "this is my text";
|
---|
39 |
|
---|
40 | //This vector is only in this process (the pointer pointing to the
|
---|
41 | //buffer that will hold the MyShmString-s is not in shared memory).
|
---|
42 | //But the buffer that will hold 10 MyShmString-s is allocated from
|
---|
43 | //shared memory using StringAllocator. Since strings use a shared
|
---|
44 | //memory allocator (CharAllocator) the 10 buffers that hold
|
---|
45 | //"this is my text" text are also in shared memory.
|
---|
46 | MyShmStringVector myvector(stringallocator);
|
---|
47 | myvector.insert(myvector.begin(), 10, mystring);
|
---|
48 |
|
---|
49 | //This vector is fully constructed in shared memory. All pointers
|
---|
50 | //buffers are constructed in the same shared memory segment
|
---|
51 | //This vector can be safely accessed from other processes.
|
---|
52 | MyShmStringVector *myshmvector =
|
---|
53 | shm.construct<MyShmStringVector>("myshmvector")(stringallocator);
|
---|
54 | myshmvector->insert(myshmvector->begin(), 10, mystring);
|
---|
55 |
|
---|
56 | //Destroy vector. This will free all strings that the vector contains
|
---|
57 | shm.destroy_ptr(myshmvector);
|
---|
58 | return 0;
|
---|
59 | }
|
---|