DEV Community

Can Gulmez
Can Gulmez

Posted on

POSIX Shared Memory

POSIX shared memory allows to us to share a mapped region between unrelated processes without needing to create a corresponding file.

Linux uses a dedicated tmpfs file system mounted under the directory /dev/shm. This file system has kernel persistance - the shared memory objects that it contains will persists even if no process currently has them open, but they will be lost if the system is shut down.

To use a POSIX shared memory object, we perform two steps:

  • Use the shm_open() function to open an object with a specified name. The shm_open() function is analogous to the open() system call. It either creates a new shared memory object or opens an existing object. As its function result, shm_open() returns a file descriptor referring to the object.

  • Pass the file descriptor obtained in the previous step in a call to mmap() that specifies MAP_SHARED in the flags argument. This maps the shared memory object into the process's virtual address space.

#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl.h>           /* For O_* constants */

int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
Enter fullscreen mode Exit fullscreen mode

The name argument identifies the shared memory object to be created or opened. The oflags argument is a mask of bits of O_* as being in open() system call.

At any point, we can apply fstat() to the file descriptor returned by shm_open() in order to obtain a stat structure whose contain information about the shared memory object.

Example of creating a POSIX shared memory is here.

After created the memory object, we of course want to read and write the data into that. Data reading program is here and writing program is here.

SUSv3 requires that POSIX shared memory objects have at least kernel persistence; that is, they continue to exist until they are explicitly removed or the system is rebooted. When a shared memory object is no longer required, it should be removed using shm_unlink(). The example program of its usage is here.

In summary, a POSIX shared memory object is used to share a region of memory between unrelated processes without creating an underlying disk file. To do this, we replace the call to open() that normally precedes mmap() with a call to shm_open(). The shm_open() call creates a file in a memory-based file system, and we can employ traditional file descriptor system calls to perform various operations on this virtual file. In particular, ftruncate() must be used to set the size of the shared memory object, since initially it has a length of zero.

Top comments (0)