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 the open() call, returning a file descriptor.
  • The file descriptor is then passed to the mmap() function that specifies the MAP_SHARED flag, mapping the memory object into the process’ virtual address space.

Creating Shared Memory Object

#include <fcntl.h>		/* Defines O_* constants */
#include <sys/stat.h> 		/* Defines mode constants */
#include <sys/mman.h>
int shm_open(const char *name, int oflag, mode_t mode);

The oflag specifies the behavior of the call, the values provided are

  • O_CREATE - create the object if it doesn’t exists
  • O_EXCL - with O_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

#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);

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.