Is fattuncate a shared memory object safe after it has ben mmap'ed?

  • shm_open()
  • mmap() with a predefined large length
  • fork() (several times)
  • ftruncate() optional

The fact is that each process created by fork() has a common segment at the same address. However, I do not want the RAM to work constantly, but dynamically change its size (with a size of 0 - a large length ).

Could this work? Is there any UB?

+7
source share
3 answers

No, that’s good. You can trim the base file at any time, but you can get SIGBUS if you access memory beyond the boundaries of the file. Thus, you need to be extremely careful not to touch the memory beyond the current file length (or catch SIGBUS and deal with it).

From man 2 mmap :

Using the displayed area may result in the following signals:

SIGBUS An attempt to access a portion of the buffer that does not match the file (for example, outside the file, including the case where another process truncates the file).

+8
source

Do not resize it.

I do not want the RAM occupied all the time

What the kernel will do for you with virtual memory. It will be called when necessary / if necessary, unless you use mlock() or MAP_LOCKED .

+1
source

Create mappings as much as possible, it will not "keep RAM busy" unless you actually use it.

If you are worried that the RAM lesson is busy after you do this, call madvise(MADV_DONTNEED) - this will clear the pages and return you new pages from the zero pool if you receive them again.

+1
source

All Articles