shm_open()
mmap()
with a predefined big length
fork()
(several times)ftruncate()
at willThe point of this is to make sure that every process spawned by fork()
have a shared segment at the same address. Yet, I don't want to keep the RAM busy all the time, but dynamically resize it (with size spanning 0 - big length
).
Can this work? Is there UB?
The main difference between System V shared memory (shmem) and memory mapped I/O (mmap) is that System V shared memory is persistent: unless explicitly removed by a process, it is kept in memory and remains available until the system is shut down.
If fildes refers to a shared memory object, ftruncate() shall set the size of the shared memory object to length.
The mmap() function establishes a mapping between a process' address space and a stream file. The address space of the process from the address returned to the caller, for a length of len, is mapped onto a stream file starting at offset off.
mmap works by manipulating your process's page table, a data structure your CPU uses to map address spaces. The CPU will translate "virtual" addresses to "physical" ones, and does so according to the page table set up by your kernel. When you access the mapped memory for the first time, your CPU generates a page fault.
No, that's fine. You can truncate the underlying file anytime, but you may receive SIGBUS
if you access the memory beyond the file's bounds. So, you will need to be extremely careful not to touch memory beyond the current length of the file (or catch SIGBUS
and deal with it).
From man 2 mmap
:
Use of a mapped region can result in these signals:
SIGBUS
Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With