### Examples of Permissions Usage Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Demonstrates setting default, unrestricted, and custom POSIX permissions for resources. ```cpp // Read for owner, read for others bip::permissions perm; perm.set_default(); // World-readable and writable bip::permissions perm2; perm2.set_unrestricted(); // Custom POSIX permissions bip::permissions perm3(0755); ``` -------------------------------- ### Example Usage of Map Options Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Constructs a mapped region using default map options. ```cpp bip::mapped_region region(shm, bip::read_write, 0, size, nullptr, bip::default_map_options); ``` -------------------------------- ### Shared Memory Vector Construction Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Demonstrates the construction of a vector within a managed shared memory segment using a custom allocator. This example shows how to define and initialize shared memory containers. ```cpp typedef bip::allocator ShmAllocator; typedef bip::vector ShmVector; bip::managed_shared_memory msm(bip::open_or_create, "seg", 65536); ShmVector *vec = msm.find_or_construct("vec") (ShmAllocator(msm.get_segment_manager())); ``` -------------------------------- ### Shared Memory Shared Pointer Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md A complete example demonstrating the creation and usage of a shared_ptr within a Boost.Interprocess managed shared memory segment. ```cpp #include #include #include namespace bip = boost::interprocess; struct Data { int value; Data(int v = 0) : value(v) {} }; int main() { try { // Create segment bip::managed_shared_memory msm( bip::open_or_create, "SmartPtrSegment", 65536 ); // Allocator for allocating in shared memory typedef bip::allocator DataAlloc; DataAlloc alloc(msm.get_segment_manager()); // Create a shared_ptr in shared memory bip::shared_ptr *sp_ptr = msm.find_or_construct>("mydata") (new(alloc.allocate(1)) Data(42), bip::default_deleter()); // Use it std::cout << "Value: " << sp_ptr->get()->value << '\n'; // Reference count increases when accessed from another process // Cleanup msm.destroy>("mydata"); bip::managed_shared_memory::remove("SmartPtrSegment"); } catch (const bip::interprocess_exception &e) { std::cerr << "Error: " << e.what() << '\n'; } return 0; } ``` -------------------------------- ### Example Usage of Mode Enumeration Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Demonstrates opening a shared memory object with read-write access. ```cpp boost::interprocess::shared_memory_object shm( boost::interprocess::open_or_create, "data", boost::interprocess::read_write // mode_t value ); ``` -------------------------------- ### Complete Interprocess Error Handling Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/08-exceptions.md A comprehensive example demonstrating the use of managed shared memory, named mutexes, and scoped locks for synchronized data access. It includes robust exception handling for memory, lock, and general interprocess errors. ```cpp #include #include #include #include #include namespace bip = boost::interprocess; struct SharedData { int counter; int array[100]; }; int main() { const char *segment_name = "DataSegment"; const char *mutex_name = "DataMutex"; try { // Create segment bip::managed_shared_memory msm( bip::open_or_create, segment_name, 65536 ); // Construct shared data SharedData *data = msm.find_or_construct("data")(); if (!data) { throw bip::interprocess_exception("Failed to construct data"); } // Create named mutex for synchronization bip::named_mutex mtx(bip::open_or_create, mutex_name); // Protected access { bip::scoped_lock lock(mtx); data->counter++; // Try to access with bounds checking if (data->counter < 100) { data->array[data->counter] = data->counter * 2; } // Note: No explicit bounds check in the code; would need to add } std::cout << "Counter: " << data->counter << '\n'; // Cleanup msm.destroy("data"); bip::managed_shared_memory::remove(segment_name); bip::named_mutex::remove(mutex_name); } catch (const bip::bad_alloc &e) { std::cerr << "Memory error: " << e.what() << '\n'; return 1; } catch (const bip::lock_exception &e) { std::cerr << "Synchronization error: " << e.what() << '\n'; return 2; } catch (const bip::interprocess_exception &e) { std::cerr << "Interprocess error: " << e.what() << '\n'; std::cerr << "Error code: " << e.get_error_code() << '\n'; return 3; } catch (const std::exception &e) { std::cerr << "Standard exception: " << e.what() << '\n'; return 4; } return 0; } ``` -------------------------------- ### Examples of Creation Tag Usage Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Illustrates using creation tags to manage shared memory segments and file mappings with different creation/opening strategies. ```cpp // Create (fail if exists) bip::managed_shared_memory msm(bip::create_only, "segment", 65536); // Open or create (succeed either way) bip::managed_shared_memory msm2(bip::open_or_create, "segment", 65536); // Open read-only bip::file_mapping fm("file.bin", bip::read_only); ``` -------------------------------- ### Interprocess Semaphore Usage Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/04-synchronization-primitives.md Demonstrates basic producer-consumer synchronization using interprocess_semaphore in shared memory. ```cpp #include namespace bip = boost::interprocess; int main() { bip::managed_shared_memory segment( bip::open_or_create, "shared", 65536 ); bip::interprocess_semaphore *sem = segment.find_or_construct("semaphore")(0); // Producer: post (increment) sem->post(); // Consumer: wait (decrement, blocking if zero) sem->wait(); return 0; } ``` -------------------------------- ### Full Usage Example: Memory-Mapped File Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Demonstrates creating a file, mapping it into memory, reading, modifying, and cleaning up using file_mapping and mapped_region. Includes error handling. ```cpp #include #include #include #include namespace bip = boost::interprocess; int main() { try { // Create a file first { std::ofstream file("example.bin", std::ios::binary); const char data[] = "Hello, Memory-Mapped File!"; file.write(data, sizeof(data)); } // Map the file bip::file_mapping fm("example.bin", bip::read_write); // Determine file size bip::offset_t file_size; fm.get_size(file_size); std::cout << "File size: " << file_size << '\n'; // Create a mapped region covering the entire file bip::mapped_region region(fm, bip::read_write, 0, file_size); // Access and modify the file through the region char *base = static_cast(region.get_address()); std::cout << "File contents: " << base << '\n'; // Modify through the mapping base[0] = 'J'; // Change 'H' to 'J' std::cout << "Modified: " << base << '\n'; // Clean up bip::file_mapping::remove("example.bin"); } catch (const bip::interprocess_exception &e) { std::cerr << "Error: " << e.what() << '\n'; } return 0; } ``` -------------------------------- ### Complete Example of Managed Mapped File Usage Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Demonstrates creating, opening, constructing a map, adding/updating records, reading data, and displaying file statistics using managed mapped files. ```cpp #include #include #include #include #include #include namespace bip = boost::interprocess; struct Record { int id; char name[256]; }; int main() { const char *filename = "/tmp/database.mmap"; try { // Create or open bip::managed_mapped_file mmf( bip::open_or_create, filename, 1048576 // 1 MB ); // Define types typedef bip::allocator, bip::managed_mapped_file::segment_manager> MapAllocator; typedef bip::map, MapAllocator> RecordMap; // Construct or find map RecordMap *map = mmf.find_or_construct("records") (std::less(), MapAllocator(mmf.get_segment_manager())); // Add or update records if (map->find(1) == map->end()) { Record r{1, "Alice"}; map->insert({1, r}); } Record r2{2, "Bob"}; (*map)[2] = r2; // Read back auto it = map->find(1); if (it != map->end()) { std::cout << "ID " << it->first << ": " << it->second.name << '\n'; } // Display statistics std::cout << "File size: " << mmf.get_size() << " bytes\n"; std::cout << "Free: " << mmf.get_free_memory() << " bytes\n"; // File persists after program exits // Cleanup explicitly if desired // bip::managed_mapped_file::remove(filename); } catch (const bip::interprocess_exception &e) { std::cerr << "Error: " << e.what() << '\n'; return 1; } return 0; } ``` -------------------------------- ### Multi-Process Access Patterns for Mapped Files Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Illustrates how different processes can create, read, and modify a managed mapped file. Includes an example of growing the file if space is insufficient. ```cpp // Process 1: Create database { bip::managed_mapped_file mmf(bip::create_only, "db.mmap", 1048576); MyDataType *data = mmf.construct("data")(/* args */); } // Process 2: Read the database (any time later) { bip::managed_mapped_file mmf(bip::open_only, "db.mmap"); MyDataType *data = mmf.find("data").first; // Use data } // Process 3: Modify and grow if needed { bip::managed_mapped_file mmf(bip::open_only, "db.mmap"); if (mmf.get_free_memory() < 1000) { mmf.grow(1048576); // Add more space } MyDataType *data = mmf.find("data").first; // Modify data } ``` -------------------------------- ### Interprocess Semaphore Constructor Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/04-synchronization-primitives.md Initializes a semaphore with a specified starting count. Throws interprocess_exception on error. ```cpp explicit interprocess_semaphore(unsigned int initialCount); ``` -------------------------------- ### Usage Example: Shared Memory with Mapped Region Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/03-mapped-region.md Demonstrates creating, mapping, and interacting with shared memory using Boost.Interprocess. Includes data initialization and cleanup. ```cpp #include #include #include #include namespace bip = boost::interprocess; // A data structure to be shared struct SharedData { int counter; char message[256]; }; int main() { try { // Create shared memory bip::shared_memory_object shm( bip::open_or_create, "shared_data", bip::read_write ); // Set size for SharedData bip::offset_t size; if (!shm.get_size(size) || size == 0) { shm.truncate(sizeof(SharedData)); } // Map it bip::mapped_region region(shm, bip::read_write); // Initialize or access data SharedData *data = new (region.get_address()) SharedData(); data->counter = 0; std::strcpy(data->message, "Hello from interprocess!"); // Simulate operations for (int i = 0; i < 10; ++i) { data->counter++; std::cout << "Counter: " << data->counter << ", Message: " << data->message << '\n'; } // Clean up bip::shared_memory_object::remove("shared_data"); } catch (const bip::interprocess_exception &e) { std::cerr << "Interprocess error: " << e.what() << '\n'; } return 0; } ``` -------------------------------- ### Full Shared Memory Object Usage Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/01-shared-memory-object.md Demonstrates the complete lifecycle of a shared memory object, including creation, mapping, usage, and cleanup. Includes error handling for interprocess exceptions. ```cpp #include #include #include namespace bip = boost::interprocess; int main() { try { // Create or open a shared memory segment bip::shared_memory_object shm( bip::open_or_create, "my_segment", bip::read_write ); // Allocate 1024 bytes if newly created bip::offset_t size; if (!shm.get_size(size) || size == 0) { shm.truncate(1024); } // Map into address space bip::mapped_region region(shm, bip::read_write); // Use the region std::cout << "Segment mapped at: " << region.get_address() << '\n'; // Clean up bip::shared_memory_object::remove("my_segment"); } catch (const bip::interprocess_exception &e) { std::cerr << "Interprocess error: " << e.what() << '\n'; } return 0; } ``` -------------------------------- ### Interprocess Mutex Usage Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/04-synchronization-primitives.md Demonstrates acquiring and releasing an interprocess_mutex using RAII with scoped_lock for protected sections in shared memory. ```cpp #include #include #include namespace bip = boost::interprocess; int main() { bip::managed_shared_memory segment( bip::open_or_create, "shared", 65536 ); // Find or construct a mutex in shared memory bip::interprocess_mutex *mtx = segment.find_or_construct("mutex")(); { // RAII lock (recommended) bip::scoped_lock lock(*mtx); // Protected section } // Automatically unlocked here return 0; } ``` -------------------------------- ### Interprocess Recursive Mutex Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/04-synchronization-primitives.md Demonstrates the usage of interprocess_recursive_mutex, showing that the same thread can lock it multiple times without deadlocking. ```cpp #include namespace bip = boost::interprocess; int main() { bip::managed_shared_memory segment( bip::open_or_create, "shared", 65536 ); bip::interprocess_recursive_mutex *rmtx = segment.find_or_construct("rmutex")(); // Same thread can lock multiple times rmtx->lock(); rmtx->lock(); // Does not deadlock rmtx->unlock(); rmtx->unlock(); return 0; } ``` -------------------------------- ### Offset Type Usage Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Demonstrates how to retrieve the size of a shared memory object using the offset_t type. This example shows a common pattern for querying segment properties. ```cpp boost::interprocess::offset_t size = 0; if (shm.get_size(size)) { std::cout << "Size: " << size << " bytes\n"; } ``` -------------------------------- ### Complete Managed Shared Memory Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Demonstrates the creation and usage of a managed shared memory segment, including defining custom allocators and containers like vectors. It shows how to find or construct a container within the shared memory and perform basic operations. ```cpp #include #include #include #include namespace bip = boost::interprocess; int main() { // Create segment with specified types bip::managed_shared_memory msm( bip::open_or_create, // open_or_create_t tag "MySegment", // const char* name 65536 // size_t (offset_t) ); // Define types typedef bip::allocator ShmAllocator; typedef bip::vector ShmVector; // Create container ShmVector *vec = msm.find_or_construct("myvector") (ShmAllocator(msm.get_segment_manager())); // Use with standard operations vec->push_back(10); bip::managed_shared_memory::remove("MySegment"); return 0; } ``` -------------------------------- ### weak_ptr Lock Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Demonstrates how to use the lock() method of weak_ptr to safely access an object that might have been deallocated. ```cpp bip::shared_ptr sp(new int(10)); bip::weak_ptr wp = sp; if (auto locked = wp.lock()) { std::cout << *locked << '\n'; } else { std::cout << "Object has been deleted\n"; } ``` -------------------------------- ### Complete Managed Shared Memory Usage Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/05-managed-shared-memory.md Demonstrates the complete lifecycle of a managed shared memory segment, including creation, object construction (a map in this case), usage, and cleanup. Includes error handling for interprocess exceptions. ```cpp #include #include #include #include #include namespace bip = boost::interprocess; typedef bip::allocator ShmAllocator; typedef bip::map, ShmAllocator> ShmMap; int main() { try { // Create segment bip::managed_shared_memory msm( bip::create_only, "MyShmSegment", 65536 ); // Construct a map in shared memory const char *name = "MyMap"; ShmMap *mymap = msm.construct(name) (std::less(), msm.get_segment_manager()); // Use the map (*mymap)["key1"] = 100; (*mymap)["key2"] = 200; // Find and display auto it = mymap->find("key1"); if (it != mymap->end()) { std::cout << "key1 = " << it->second << '\n'; } // Cleanup msm.destroy(name); bip::managed_shared_memory::remove("MyShmSegment"); } catch (const bip::interprocess_exception &e) { std::cerr << "Error: " << e.what() << '\n'; } return 0; } ``` -------------------------------- ### unique_ptr Pointer Constructor Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Demonstrates creating a unique_ptr by taking ownership of a raw pointer. The managed object will be deleted when the unique_ptr goes out of scope. ```cpp int *raw = new int(42); bboost::interprocess::unique_ptr uptr(raw); // uptr now owns the int; it will be deleted when uptr is destroyed ``` -------------------------------- ### unique_ptr with Custom Deleter Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Shows how to construct a unique_ptr with a custom deleter, such as 'free' for C-style memory allocation. This allows managing resources allocated by functions other than 'new'. ```cpp void *buffer = malloc(1024); bip::unique_ptr ptr(buffer, &free); // Uses free() instead of delete ``` -------------------------------- ### Minimum Shared Memory Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/00-overview.md Creates a shared memory segment, finds or constructs an integer named 'x', and increments it. Multiple processes can execute this code to share and modify the integer. ```cpp #include namespace bip = boost::interprocess; int main() { bip::managed_shared_memory seg(bip::open_or_create, "seg", 65536); int *p = seg.find_or_construct("x")(0); ++(*p); } ``` -------------------------------- ### Interprocess Error Handling Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/00-overview.md Demonstrates how to catch specific Boost.Interprocess exceptions during shared memory operations. Use this pattern to handle potential allocation, synchronization, or general interprocess errors gracefully. ```cpp try { bip::managed_shared_memory msm(bip::create_only, "seg", 65536); // ... } catch (const bip::bad_alloc &e) { // Memory allocation failed } catch (const bip::lock_exception &e) { // Synchronization failed } catch (const bip::interprocess_exception &e) { // Other interprocess errors } ``` -------------------------------- ### Basic Shared Memory Usage Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/README.md Demonstrates how to create or open a managed shared memory segment, store and access a named integer, and increment it. This example is designed to be run from multiple processes simultaneously to show thread-safe incrementing of shared data. ```cpp #include namespace bip = boost::interprocess; int main() { // Create or open a managed shared memory segment bip::managed_shared_memory msm( bip::open_or_create, "my_segment", 65536 // 64 KB ); // Store or find a named integer int *my_int = msm.find_or_construct("counter")(0); // Use it (thread-safe across processes) ++(*my_int); return 0; } ``` -------------------------------- ### unique_ptr release Method Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Shows how to release ownership of the managed pointer from a unique_ptr, making the unique_ptr null. The caller becomes responsible for managing the returned raw pointer. ```cpp int *raw = uptr.release(); // uptr is now null; caller responsible for deleting raw delete raw; ``` -------------------------------- ### shared_ptr get() Method Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md The get() method returns the raw pointer managed by the shared_ptr. This operation is non-const, thread-safe, and never throws. ```cpp T *get() const noexcept; ``` -------------------------------- ### Recommended Initialization Pattern Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/00-overview.md Illustrates the recommended way to initialize and use managed shared memory. This pattern ensures proper segment creation/opening, type definition, and shared data access, with automatic cleanup handled by destructors. ```cpp namespace bip = boost::interprocess; int main() { try { // Create or open segment bip::managed_shared_memory seg( bip::open_or_create, "MySegment", 1048576 // 1 MB ); // Define types once typedef bip::allocator IntAlloc; // Access or create shared data int *my_int = seg.find_or_construct("my_int")(0); // Use ++(*my_int); // No explicit cleanup; destruction is automatic } catch (const bip::interprocess_exception &e) { std::cerr << "IPC Error: " << e.what() << '\n'; return 1; } return 0; } ``` -------------------------------- ### Managed Mapped File Growth Recommendation Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Contrasts allocating sufficient space upfront with frequent, small growths, highlighting the performance implications. It is recommended to allocate ample space initially. ```cpp // Good: Allocate plenty upfront bip::managed_mapped_file mmf(bip::create_only, "large.mmap", 1000000000); // Avoid: Frequent small growths bip::managed_mapped_file mmf(bip::create_only, "small.mmap", 1024); // ... later ... for (int i = 0; i < 1000; ++i) { mmf.grow(100); // Bad: expensive } ``` -------------------------------- ### get Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/06-offset-ptr.md Returns the raw pointer to the object currently pointed to by the offset_ptr. This operation is safe and does not throw exceptions. ```APIDOC ## get ### Description Retrieves the underlying raw pointer that the `offset_ptr` is managing. This allows for direct interaction with the pointed-to object using standard pointer operations. ### Signature ```cpp pointer get() const noexcept; ``` ### Returns The raw pointer to the pointed-to object. ### Example ```cpp int *raw = p.get(); ``` ``` -------------------------------- ### Open-or-Create Constructor for Managed Mapped File Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Opens an existing file or creates it if it doesn't exist. The size and permissions parameters are ignored if the file already exists. Throws interprocess_exception on error. ```cpp basic_managed_mapped_file(open_or_create_t, const char *name, size_type size, const void *addr = 0, const permissions &perm = permissions()); ``` -------------------------------- ### Get Mapping Handle Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Obtains an opaque handle to the underlying file mapping. This handle can be used to construct a mapped_region. ```cpp mapping_handle_t get_mapping_handle() const noexcept; ``` ```cpp boost::interprocess::file_mapping fm("file.bin", boost::interprocess::read_write); boost::interprocess::mapped_region region(fm, boost::interprocess::read_write); ``` -------------------------------- ### Get Access Mode Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Retrieves the access mode (read_write or read_only) specified during the file_mapping object's construction. ```cpp mode_t get_mode() const noexcept; ``` -------------------------------- ### Get Mapped Filename using file_mapping::get_name Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Retrieves the name of the file associated with the file_mapping. This is the filename that was passed to the constructor. ```cpp boost::interprocess::file_mapping fm("data.bin", boost::interprocess::read_write); std::cout << "Mapping file: " << fm.get_name() << '\n'; ``` -------------------------------- ### File Open Constructor for file_mapping Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Opens a specified file for memory mapping. The file must exist and appropriate permissions must be granted. Throws interprocess_exception on failure. ```cpp boost::interprocess::file_mapping fm( "/path/to/file.dat", boost::interprocess::read_write ); ``` -------------------------------- ### Get Total Size of Managed Mapped File Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Returns the total size of the mapped file in bytes. This operation does not throw exceptions. ```cpp size_type get_size() const; ``` -------------------------------- ### File-Based Persistence Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/README.md Illustrates how to create persistent data using a file-backed managed memory map. The data stored in this segment will survive process termination and restarts. ```cpp #include int main() { // Create persistent data using a file bip::managed_mapped_file mmf( bip::open_or_create, "/tmp/database.mmap", 1048576 // 1 MB ); // Data survives process termination and restarts int *data = mmf.find_or_construct("persistent")(42); } ``` -------------------------------- ### Offset Type Definitions Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/09-types.md Defines the default `offset_type` for `offset_ptr` and shows examples of using `offset_ptr` with standard and custom offset types. ```cpp // Default offset type for offset_ptr typedef std::size_t offset_type; // Typical usage typedef boost::interprocess::offset_ptr offset_int_ptr; typedef boost::interprocess::offset_ptr offset_myclass_ptr; // Custom offset type (for cross-architecture communication) typedef boost::interprocess::offset_ptr offset_int64_ptr; ``` -------------------------------- ### Standard C++ Code Samples Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/README.md This section outlines the conventions used for code blocks within the documentation, indicating that standard C++ code samples will be presented. ```cpp // Standard C++ code samples ``` -------------------------------- ### unique_ptr operator bool Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Demonstrates checking if a unique_ptr manages a valid object using its explicit conversion to bool. This is useful for conditional operations. ```cpp if (uptr) { // Use *uptr } ``` -------------------------------- ### Open-or-Create Constructor Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/05-managed-shared-memory.md Opens an existing shared memory segment or creates it if it does not exist. The `size` and `perm` parameters are ignored if the segment already exists. ```APIDOC ## basic_managed_shared_memory(open_or_create_t, const char *name, size_type size, const void *addr = 0, const permissions &perm = permissions()) ### Description Opens an existing shared memory segment or creates it if it does not exist. If the segment exists, the `size` and `perm` parameters are ignored. ### Parameters #### Path Parameters - **tag** (`open_or_create_t`) - Required - Pass `boost::interprocess::open_or_create`. - **name** (`const char*`) - Required - Unique segment name. - **size** (`size_type`) - Required - Size in bytes to allocate if creating. - **addr** (`const void*`) - Optional - Hint for base address (page-aligned); OS may ignore. Defaults to `0`. - **perm** (`permissions`) - Optional - Access permissions if creating. Defaults to `permissions()`. ### Effects Opens an existing segment or creates it if it doesn't exist. ### Throws `interprocess_exception` on error. ``` -------------------------------- ### Get Free Memory in Managed Mapped File Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Returns the number of unallocated bytes currently available within the mapped file. This operation does not throw exceptions. ```cpp size_type get_free_memory() const; ``` -------------------------------- ### Advise OS on memory access patterns Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/03-mapped-region.md Provides a hint to the OS kernel about expected access patterns for a specified range within the mapped region. This is a no-op on platforms without madvise support. Advice codes are platform-specific. ```cpp void advise(void *addr, std::size_t length, int advice) noexcept; ``` ```cpp #ifdef MADV_SEQUENTIAL bip::mapped_region region(shm, bip::read_write); region.advise(region.get_address(), region.get_size(), MADV_SEQUENTIAL); #endif ``` -------------------------------- ### Get Mapping Handle for Shared Memory Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/01-shared-memory-object.md Retrieves an opaque handle for a shared memory object, suitable for passing to the mapped_region constructor. This function does not throw exceptions. ```cpp mapping_handle_t get_mapping_handle() const noexcept; ``` -------------------------------- ### Get File Size Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Retrieves the size of the mapped file in bytes. Writes the size to the provided offset_t reference. Returns true on success, false otherwise. ```cpp bool get_size(offset_t &size) const noexcept; ``` ```cpp boost::interprocess::file_mapping fm("data.bin", boost::interprocess::read_only); boost::interprocess::offset_t sz = 0; if (fm.get_size(sz)) { std::cout << "File size: " << sz << " bytes\n"; } ``` -------------------------------- ### Open-or-Create Constructor Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/01-shared-memory-object.md Creates a named shared memory segment if it does not exist; otherwise, opens the existing segment. Throws `interprocess_exception` on error. ```APIDOC ## Open-or-Create Constructor ### Description Creates a named shared memory segment if it does not exist; otherwise, opens the existing segment. ### Constructor Signature ```cpp shared_memory_object(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions()); ``` ### Parameters #### Path Parameters - **tag** (`open_or_create_t`) - Required - Tag object, pass `boost::interprocess::open_or_create` - **name** (`const char*`) - Required - Identifier for the shared memory segment - **mode** (`mode_t`) - Required - Access mode: `read_write` or `read_only` - **perm** (`permissions`) - Optional - Applied only if creation occurs. Defaults to `permissions()`. ### Effects Creates a named shared memory segment if it does not exist; otherwise opens the existing segment. ### Throws `interprocess_exception` on error. ### Example ```cpp boost::interprocess::shared_memory_object shm( boost::interprocess::open_or_create, "shared_data", boost::interprocess::read_write ); ``` ``` -------------------------------- ### Producer-Consumer with Interprocess Mutex and Condition Variable Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/04-synchronization-primitives.md Demonstrates a producer and consumer pattern using Boost.Interprocess managed shared memory, interprocess_mutex, and interprocess_condition. The producer sets data and notifies, while the consumer waits for data to be ready. ```cpp #include #include #include #include namespace bip = boost::interprocess; struct SharedBuffer { bip::interprocess_mutex mtx; bip::interprocess_condition cv; int data; bool ready; }; int main() { bip::managed_shared_memory segment( bip::open_or_create, "shared", 65536 ); SharedBuffer *buf = segment.find_or_construct("buffer")(); // Producer { bip::scoped_lock lock(buf->mtx); buf->data = 42; buf->ready = true; buf->cv.notify_one(); } // Consumer { bip::scoped_lock lock(buf->mtx); while (!buf->ready) { buf->cv.wait(lock); } // Use buf->data } return 0; } ``` -------------------------------- ### Get size of mapped region Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/03-mapped-region.md Returns the size of the mapped region in bytes, as specified during construction. This is the userspace mapping size, which may differ from the OS allocation size. ```cpp std::size_t get_size() const noexcept; ``` ```cpp bip::mapped_region region(shm, bip::read_write, 0, 4096); std::cout << "Mapped size: " << region.get_size() << " bytes\n"; // 4096 ``` -------------------------------- ### basic_managed_mapped_file Constructors Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Provides various constructors for creating and opening managed mapped files with different modes and options. ```APIDOC ## basic_managed_mapped_file() ### Description Creates an empty managed_mapped_file object, suitable for move assignment. ### Method Constructor ### Parameters None ### Response An uninitialized managed_mapped_file object. ### Throws Never ``` ```APIDOC ## basic_managed_mapped_file(create_only_t, const char *name, size_type size, const void *addr = 0, const permissions &perm = permissions()) ### Description Creates a new managed mapped file with the specified name, size, and permissions. The file is created only if it does not already exist. ### Method Constructor ### Parameters #### Path Parameters - **name** (const char*) - Required - Filesystem path to the file. - **size** (size_type) - Required - Initial file size in bytes. Must be at least `segment_manager::get_min_size()`. - **addr** (const void*) - Optional - Hint for the base address of the mapping. Defaults to `0`. - **perm** (permissions) - Optional - File permissions. Defaults to `permissions()`. ### Request Example ```cpp bip::managed_mapped_file mmf( bip::create_only, "/tmp/mydata.mmap", 1048576, // 1 MB nullptr, bip::permissions(0644) ); ``` ### Response A managed mapped file ready for allocation. ### Throws `interprocess_exception` if: - A file already exists at the path. - The file cannot be created or resized. - Memory mapping fails. ``` ```APIDOC ## basic_managed_mapped_file(open_or_create_t, const char *name, size_type size, const void *addr = 0, const permissions &perm = permissions()) ### Description Opens an existing managed mapped file or creates a new one if it doesn't exist. If created, it will have the specified size and permissions. ### Method Constructor ### Parameters #### Path Parameters - **name** (const char*) - Required - Filesystem path to the file. - **size** (size_type) - Required - Initial file size in bytes if the file is created. Must be at least `segment_manager::get_min_size()`. - **addr** (const void*) - Optional - Hint for the base address of the mapping. Defaults to `0`. - **perm** (permissions) - Optional - File permissions if the file is created. Defaults to `permissions()`. ### Response A managed mapped file ready for allocation. ### Throws `interprocess_exception` if: - The file cannot be opened or created. - The file cannot be resized (if created). - Memory mapping fails. ``` ```APIDOC ## basic_managed_mapped_file(open_only_t, const char *name, const void *addr = 0) ### Description Opens an existing managed mapped file exclusively. ### Method Constructor ### Parameters #### Path Parameters - **name** (const char*) - Required - Filesystem path to the file. - **addr** (const void*) - Optional - Hint for the base address of the mapping. Defaults to `0`. ### Response A managed mapped file ready for use. ### Throws `interprocess_exception` if: - The file does not exist. - The file cannot be opened. - Memory mapping fails. ``` ```APIDOC ## basic_managed_mapped_file(open_read_only_t, const char *name, const void *addr = 0) ### Description Opens an existing managed mapped file in read-only mode. ### Method Constructor ### Parameters #### Path Parameters - **name** (const char*) - Required - Filesystem path to the file. - **addr** (const void*) - Optional - Hint for the base address of the mapping. Defaults to `0`. ### Response A managed mapped file ready for read-only access. ### Throws `interprocess_exception` if: - The file does not exist. - The file cannot be opened in read-only mode. - Memory mapping fails. ``` ```APIDOC ## basic_managed_mapped_file(open_copy_on_write_t, const char *name, const void *addr = 0) ### Description Opens an existing managed mapped file in copy-on-write mode. ### Method Constructor ### Parameters #### Path Parameters - **name** (const char*) - Required - Filesystem path to the file. - **addr** (const void*) - Optional - Hint for the base address of the mapping. Defaults to `0`. ### Response A managed mapped file ready for copy-on-write access. ### Throws `interprocess_exception` if: - The file does not exist. - The file cannot be opened in copy-on-write mode. - Memory mapping fails. ``` -------------------------------- ### Create mapped_region from file_mapping Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/02-file-mapping.md Illustrates how to create a mapped_region object from an existing file_mapping to access file data in memory. ```cpp bip::file_mapping fm("file.bin", bip::read_write); bip::mapped_region region(fm, bip::read_write); void *addr = region.get_address(); // Can now access file data ``` -------------------------------- ### Constructors Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Provides constructors for opening or creating managed mapped files with various options. ```APIDOC ## Constructors ### Open-or-Create Constructor ```cpp basic_managed_mapped_file(open_or_create_t, const char *name, size_type size, const void *addr = 0, const permissions &perm = permissions()); ``` **Effects:** Opens an existing file or creates it if it doesn't exist. **Throws:** `interprocess_exception` on error. **Notes:** If the file exists, `size` and `perm` parameters are ignored. ### Open-Only Constructor ```cpp basic_managed_mapped_file(open_only_t, const char *name, const void *addr = 0); ``` **Effects:** Opens an existing file in read-write mode. **Throws:** `interprocess_exception` if the file doesn't exist. ### Open-Read-Only Constructor ```cpp basic_managed_mapped_file(open_read_only_t, const char *name, const void *addr = 0); ``` **Effects:** Opens an existing file in read-only mode. **Throws:** `interprocess_exception` if the file doesn't exist. ### Open-Copy-on-Write Constructor ```cpp basic_managed_mapped_file(open_copy_on_write_t, const char *name, const void *addr = 0); ``` **Effects:** Opens with copy-on-write semantics (changes are private). **Throws:** `interprocess_exception` if the file doesn't exist. ### Move Constructor and Assignment ```cpp basic_managed_mapped_file(basic_managed_mapped_file &&moved); basic_managed_mapped_file &operator=(basic_managed_mapped_file &&moved); ``` **Effects:** Transfers ownership from `moved` to `*this`. **Throws:** Never ``` -------------------------------- ### Static Methods Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Provides static utility functions for managing mapped files. ```APIDOC ## Static Methods ### remove (static) ```cpp static bool remove(const char *name); ``` | Parameter | Type | Description | |-----------|------|-------------| | name | `const char*` | Path to the file to remove | **Returns:** `true` if removed or didn't exist; `false` on error. **Effects:** Deletes the mapped file from the filesystem. **Throws:** Never **Notes:** File must be closed by all processes before successful deletion on some platforms. ``` -------------------------------- ### Get Raw Pointer from Offset Pointer Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/06-offset-ptr.md Retrieves the underlying raw pointer managed by the offset_ptr. This method is useful when you need to interact with C APIs or other functions that expect a raw pointer. ```cpp pointer get() const noexcept; ``` ```cpp int *raw = p.get(); ``` -------------------------------- ### Type Signatures in C++ Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/README.md Illustrates the convention for presenting C++ type signatures, including class definitions, method declarations, parameter types, and exception specifications. ```cpp class Name { void method(Type param) noexcept; }; ``` -------------------------------- ### unique_ptr Move Constructor and Assignment Example Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/11-smart-pointers.md Illustrates transferring ownership of a managed object from one unique_ptr to another using move semantics. The source unique_ptr becomes null after the move. ```cpp bip::unique_ptr p1(new int(10)); bip::unique_ptr p2 = std::move(p1); assert(!p1); // p1 is now null assert(*p2 == 10); ``` -------------------------------- ### Synchronization with Interprocess Mutex Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Demonstrates how to use `boost::interprocess::interprocess_mutex` and `boost::interprocess::scoped_lock` for process-safe synchronization within a `managed_mapped_file`. This is essential when multiple processes access shared data. ```cpp struct SyncedData { bip::interprocess_mutex mtx; int counter; }; bip::managed_mapped_file mmf(bip::open_or_create, "sync.mmap", 65536); SyncedData *sd = mmf.find_or_construct("data")(); { bip::scoped_lock lock(sd->mtx); ++sd->counter; } ``` -------------------------------- ### advise Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/03-mapped-region.md Provides a hint to the OS kernel about expected access patterns for a specified range within the mapped region. ```APIDOC ## advise ### Description Provides a hint to the OS kernel about expected access patterns. This is a no-op on platforms without `madvise` support. ### Method `void advise(void *addr, std::size_t length, int advice) noexcept` ### Parameters #### Path Parameters - **addr** (`void*`) - Required - Address within the mapped region - **length** (`std::size_t`) - Required - Number of bytes to advise on - **advice** (`int`) - Required - Advice flags (platform-dependent, typically from madvise) ### Notes Advice codes are platform-specific. On POSIX systems, these correspond to `madvise()` constants: - `MADV_NORMAL`: No special access pattern (default) - `MADV_SEQUENTIAL`: Data accessed sequentially - `MADV_RANDOM`: Data accessed randomly - `MADV_WILLNEED`: Data will be accessed soon - `MADV_DONTNEED`: Data is no longer needed (platform-dependent behavior) ``` -------------------------------- ### Get base address of mapped region Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/03-mapped-region.md Retrieves the pointer to the base address of the mapped region in virtual memory. Returns nullptr if the region is empty. The address corresponds to the offset specified during construction. ```cpp void *get_address() const noexcept; ``` ```cpp bip::mapped_region region(shm, bip::read_write); void *base = region.get_address(); if (base) { int *p = static_cast(base); *p = 123; } ``` -------------------------------- ### Open-Only Constructor for Managed Mapped File Source: https://github.com/boostorg/interprocess/blob/develop/_autodocs/10-managed-mapped-file.md Opens an existing file in read-write mode. Throws interprocess_exception if the file does not exist. ```cpp basic_managed_mapped_file(open_only_t, const char *name, const void *addr = 0); ```