Using `mmap` to Create Shared Objects
- November 20, 2019
- Liu, An-Chi 劉安齊
When you have many processes and want to implement shared memory to handle shared data, you can use shared memory to build the solution. To create shared memory, you can use mmap or System V shmget. However, according to the Stack Overflow answer “(How to use shared memory with Linux in C)”, shmget is somewhat outdated, while mmap is newer and more flexible.
Shared memory allows us to create a region of memory that can be shared. mmap returns a pointer to that region, with type void *. If we want to put data into it, we can use memcpy to copy objects, strings, or anything else into the shared region. We can also cast the void * directly to an object pointer—this way we create a shared object, and different processes can access the object directly.