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

linux, memory-management, posix, shared-memory

Solution

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

Problem

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

Original source