POSIX Shared Memory
It’s possible to create shared memory objects on POSIX and there are different reasons to do that. For example it might be useful to share data among different processes or to read input from files of big dimension. To do that some operations are usually performed
- The
shm_open()
function open an object with the specified name. It behave similar to theopen()
call, returning a file descriptor. - The file descriptor is then passed to the
mmap()
function that specifies theMAP_SHARED
flag, mapping the memory object into the process’ virtual address space.
Creating Shared Memory Object
The oflag
specifies the behavior of the call, the values provided are
-
O_CREATE
- create the object if it doesn’t exists -
O_EXCL
- withO_CREATE
create object exclusively -
O_RDONLY
- open object for read only -
O_RDWR
- open object for both reading and writing -
O_TRUNC
- truncate object to zero length
Since a shared memory object is identified with a file descriptor, all functions that are usually used on file can be used. A common procedure after creating the shared memory object is to set the size of the object with the ftruncate()
function. Then the object is mapped to the process address space.
Mapping Object
The mmap()
takes several parameters
- addr - indicate the address at which the the mapping is to be located
- lenght - specifies the size of the mapping in bytes
-
prot - specifies the protection to be place on the mapping
-
PROT_NONE
- the region can’t be accessed -
PROT_READ
- the contents of the region can be read -
PROT_WRITE
- the contents of the region can be modified -
PROT_EXEC
- the contents of the region can be executed
-
-
flags - specifies some properties of the shared region
-
MAP_PRIVATE
- to keep the modifications visible only to the current process -
MAP_SHARED
- modifications are visible to all process
-
Removing Shared Memory Object
The shm_unlink(const char *name)
remove the shared memory object specified by name.
Enjoy Reading This Article?
Here are some more articles you might like to read next: