Expand description
POSIX shared memory
§Example
use rustix::fs::{ftruncate, Mode};
use rustix::mm::{mmap, MapFlags, ProtFlags};
use rustix::{io, shm};
use std::mem::size_of;
use std::ptr::null_mut;
// A type describing the data to be shared.
#[repr(C)]
struct MyBufferType {
// …
}
// Create the shared memory object.
let shm_path = "/rustix-shm-example";
let fd = shm::open(
shm_path,
shm::OFlags::CREATE | shm::OFlags::EXCL | shm::OFlags::RDWR,
Mode::RUSR | Mode::WUSR,
)?;
// Resize the shared memory object to the size of our data.
ftruncate(&fd, size_of::<MyBufferType>() as u64)?;
// Map the shared memory object into our address space.
//
// SAFETY: We're creating a new mapping that's independent of any existing
// memory allocations. There are interesting things to say about *using*
// `ptr`, but that's for another safety comment.
let ptr = unsafe {
mmap(
null_mut(),
size_of::<MyBufferType>(),
ProtFlags::READ | ProtFlags::WRITE,
MapFlags::SHARED,
&fd,
0,
)?
};
// Use `ptr`…
// Remove the shared memory object name.
shm::unlink(shm_path)?;
Structs§
O_*
constants for use withshm::open
.
Functions§
shm_open(name, oflags, mode)
—Opens a shared memory object.shm_unlink(name)
—Unlinks a shared memory object.