Zero a large memory mapping with `madvise`

前端 未结 3 1597
南旧
南旧 2021-02-06 05:50

I have the following problem:

I allocate a large chunk of memory (multiple GiB) via mmap with MAP_ANONYMOUS. That chunk holds a large hash map w

3条回答
  •  北海茫月
    2021-02-06 06:10

    This madvise behavior is certainly not standard, so this wouldn't be portable.

    If the part that you want to zero out happens to be at the end of your mapping you could get away with ftruncate. You'd have to introduce one step more:

    1. shm_open to have a "persistent" file descriptor to your data
    2. ftruncate to the needed size
    3. mmap of that FD

    Then you could always

    1. munmap
    2. ftruncate to something short
    3. ftruncate to the real length you need
    4. mmap again

    and then the part that you "remapped" would be zero initialized.

    But have also in mind that the system has to do the zeroing of the pages. This might be a bit more efficient than the inline stuff that your compiler produces for memset, but that is not sure.

提交回复
热议问题