1 //////////////////////////////////////////////////////////////////////////////
3 // (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 // See http://www.boost.org/libs/interprocess for documentation.
9 //////////////////////////////////////////////////////////////////////////////
11 #ifndef BOOST_INTERPROCESS_ANONYMOUS_SHARED_MEMORY_HPP
12 #define BOOST_INTERPROCESS_ANONYMOUS_SHARED_MEMORY_HPP
14 #include <boost/interprocess/detail/config_begin.hpp>
15 #include <boost/interprocess/detail/workaround.hpp>
16 #include <boost/interprocess/creation_tags.hpp>
17 #include <boost/interprocess/detail/move.hpp>
18 #include <boost/interprocess/interprocess_fwd.hpp>
19 #include <boost/interprocess/mapped_region.hpp>
22 #if (!defined(BOOST_INTERPROCESS_WINDOWS))
23 # include <fcntl.h> //open, O_CREAT, O_*...
24 # include <sys/mman.h> //mmap
25 # include <sys/stat.h> //mode_t, S_IRWXG, S_IRWXO, S_IRWXU,
27 #include <boost/interprocess/windows_shared_memory.hpp>
32 //!Describes a function that creates anonymous shared memory that can be
33 //!shared between forked processes
36 namespace interprocess {
42 class raw_mapped_region_creator
46 create_posix_mapped_region(void *address, offset_t offset, std::size_t size)
49 region.m_base = address;
50 region.m_offset = offset;
51 region.m_extra_offset = 0;
60 //!A function that creates an anonymous shared memory segment of size "size".
61 //!If "address" is passed the function will try to map the segment in that address.
62 //!Otherwise the operating system will choose the mapping address.
63 //!The function returns a mapped_region holding that segment or throws
64 //!interprocess_exception if the function fails.
65 //static mapped_region
67 anonymous_shared_memory(std::size_t size, void *address = 0)
68 #if (!defined(BOOST_INTERPROCESS_WINDOWS))
73 #if defined(MAP_ANONYMOUS) //Use MAP_ANONYMOUS
74 flags = MAP_ANONYMOUS | MAP_SHARED;
75 #elif !defined(MAP_ANONYMOUS) && defined(MAP_ANON) //use MAP_ANON
76 flags = MAP_ANON | MAP_SHARED;
77 #else // Use "/dev/zero"
78 fd = open("/dev/zero", O_RDWR);
81 error_info err = system_error_code();
82 throw interprocess_exception(err);
87 address = mmap( address
89 , PROT_READ|PROT_WRITE
94 if(address == MAP_FAILED){
97 error_info err = system_error_code();
98 throw interprocess_exception(err);
104 return detail::raw_mapped_region_creator::create_posix_mapped_region(address, 0, size);
108 windows_shared_memory anonymous_mapping(create_only, 0, read_write, size);
109 return mapped_region(anonymous_mapping, read_write, 0, size, address);
114 } //namespace interprocess {
115 } //namespace boost {
117 #include <boost/interprocess/detail/config_end.hpp>
119 #endif //BOOST_INTERPROCESS_ANONYMOUS_SHARED_MEMORY_HPP