POSIX shared memory segments, and memory-mapped files

x::fd fd=x::fd::base::shm_open("testshm", O_RDWR|O_CREAT, 0600);


// ...


shm_open() creates or opens an existing POSIX shared memory segment. ftruncate() sets the size of the shared memory segment. shm_unlink() removes it.

The shared memory segment is referenced by a file descriptor, but it's not readable or writable, like a traditional file. It's accessed by memory-mapping it into the process's address space:

struct X;

x::mmap<X> mapped=INSERT_LIBX_NAMESPACE::mmap<X>::create(fd, PROT_READ|PROT_WRITE);

X *instance=mapped->object();


x::mmap is a reference to a reference-counted object that represents a memory-mapped segment. This is is an interface to the mmap(2) system call. The constructor maps the memory segment. When the last reference to this reference-counted object goes out of scope and it gets destroyed, the destructor call munmap(2).

The template parameter is typically a POD class, but a real object could possibly be used, if its constructor and destructor invocations are carefully handled.

The create() constructor takes the following arguments.

These parameters get forwarded to mmap(2), mostly unchanged. The optional flag value defaults to MAP_SHARED. For a file-based mapping the offset value defaults to 0. For the file-based mapping, the default length value of 0 is replaced with the current size of the file, as obtained by the stat(2) system call.

msync() calls the msync(2) system call.

object() returns a pointer to the mapped memory segment, casted to a pointer to the template type.