In the UNIX world, the standard way to create a file mapping object backed by RAM or the pagefile rather than a disk file is to call shm_open
. This creates a memory mapping with a name, and returns a file handle that you can pass to mmap
.
The problem is that it creates a name. It would be nice if I could create an anonymous memory mapping. This would solve two problems:
shm_unlink
immediately after shm_open
is one possibility, but this leaves a small window in which a sudden termination would leave the object around until the next reboot.In Linux, there is memfd_create
to solve this problem. Similarly, Windows allows passing a null name to CreateFileMappingW
to create an anonymous mapping.
Is there an equivalent for Mac OS?
You can create a file with open
and then immediately remove it from the filesystem with unlink
. The file descriptor will remain open, and the file itself will stay alive until its last descriptor is closed. This works if you need a file descriptor to share between processes, and it appears to solve the two problems that you listed.
Alternatively, passing both MAP_ANON
and MAP_SHARED
to mmap
creates a shared memory region that is not backed by any file but that is shared between this process and all of its forks. However, like any memory mapping, it is deleted on exec
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With