Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe to ftruncate a shared memory object after it has ben mmap'ed?

  • shm_open()
  • mmap() with a predefined big length
  • fork() (several times)
  • ftruncate() at will

The 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?

like image 265
Lorenzo Pistone Avatar asked Oct 29 '12 16:10

Lorenzo Pistone


People also ask

What is the difference between shared memory and mmap?

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.

What is the role of Ftruncate () when you create a shared memory object?

If fildes refers to a shared memory object, ftruncate() shall set the size of the shared memory object to length.

What does mmap actually do?

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.

How does mmap work internally?

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.


1 Answers

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).

like image 121
nneonneo Avatar answered Nov 11 '22 19:11

nneonneo