Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mac OS have a way to create an anonymous file mapping?

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:

  1. It would avoid problems where two instances of the same program may stomp on each other's mapped files.
  2. If the program crashes or otherwise suddenly terminates, it would not leave the shared memory object around. Calling 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?

like image 975
Myria Avatar asked Sep 29 '16 20:09

Myria


Video Answer


1 Answers

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.

like image 101
zneak Avatar answered Sep 18 '22 03:09

zneak