x::fd fd=x::fd::base::shm_open("testshm", O_RDWR|O_CREAT, 0600); fd->truncate(1024); // ... x::fd::base::shm_unlink("testshm");
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=x::mmap<X>::create(fd, PROT_READ|PROT_WRITE); X *instance=mapped->object(); mapped->msync();
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.
An optional void *
,
specifying the first argument to
mmap(2),
if not present it defaults to nullptr
; then either:
An open
x::fd
,
the protection setting,
and three optional parameters: flags, offset, and length. This maps
in the opened file descriptor.
A length, the protection setting, and an optional flag value. This creates a standalone mapped segment.
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.
#include <x/mmapfile.H> x::mmapfile file=x::mmapfile::create(fd, PROT_READ|PROT_WRITE); const char *ptr=file->buffer(); size_t size=file->size();
x::mmapfile
is a simplified wrapper for x::mmap
ing the
entire contents of the file, as is.
The constructor takes an open file descriptor, and the required
protection settingargument. buffer
()
returns a pointer
to the mapped file, with size
() giving
the size of the mapped file.
The msync
() method is inherited.