Lorenzo Pistone
Lorenzo Pistone

Reputation: 5188

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

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?

Upvotes: 8

Views: 4919

Answers (3)

Damon
Damon

Reputation: 70206

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

If you are worried about keeping RAM busy after you are done using it, call madvise(MADV_DONTNEED) -- this will purge the pages and give you back new pages from the zero pool if you access them again.

Upvotes: 1

Brian Cain
Brian Cain

Reputation: 14619

Don't resize it.

I don't want to keep the RAM busy all the time

That's what the kernel will do for you with virtual memory. It will be paged as necessary/appropriate as long as you don't use mlock() or MAP_LOCKED.

Upvotes: 1

nneonneo
nneonneo

Reputation: 179677

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

Upvotes: 10

Related Questions