Using Shared Memory in Linux Systems

U

Shared Memory is an efficient means of passing data between programs. One program will create a memory portion which other processes (if permitted) can access.

A process creates a shared memory segment using shmget()|. The original owner of a shared memory segment can assign ownership to another user with shmctl(). It can also revoke this assignment. Other processes with proper permission can perform various control functions on the shared memory segment using shmctl(). Once created, a shared segment can be attached to a process address space using shmat(). It can be detached using shmdt() (see shmop()). The attaching process must have the appropriate permissions for shmat(). Once attached, the process can read or write to the segment, as allowed by the permission requested in the attach operation. A shared segment can be attached multiple times by the same process. A shared memory segment is described by a control structure with a unique ID that points to an area of physical memory. The identifier of the segment is called the shmid. The structure definition for the shared memory segment control structures and prototypews can be found in <sys/shm.h>.

 The following source code is a C++ Template Class for a Shared Object

#pragma once
#include <mutex>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>

template <class T> class ShmObject 
{
private:
public:
	int sharedMemoryID;
	T* sharedMemoryPtr;
	ShmObject();
	ShmObject(int);
	void Delete();
	~ShmObject();  
	unsigned int numberOfProcesses();
};

template <class T> ShmObject<T>::ShmObject() 
{    
	sharedMemoryID = shmget(IPC_PRIVATE, sizeof(T), IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
	sharedMemoryPtr = (T*) shmat(sharedMemoryID, 0, 0);
}

template <class T> ShmObject<T>::ShmObject(int sharedMemoryIDToAttach)
{
	sharedMemoryID = sharedMemoryIDToAttach;
	sharedMemoryPtr = (T*) shmat(sharedMemoryID, 0, 0);
}

template <class T> ShmObject<T>::~ShmObject()
{
	shmdt(sharedMemoryPtr);
	shmctl(sharedMemoryID, IPC_RMID, 0);
}

template <class T> void ShmObject<T>::Delete()
{
	shmdt(sharedMemoryPtr);
	shmctl(sharedMemoryID, IPC_RMID, 0);
}

template <class T> unsigned int ShmObject<T>::numberOfProcesses() 
{
	struct shmid_ds shm_segment;
	int ret = shmctl(sharedMemoryID, IPC_STAT, &shm_segment);
	return shm_segment.shm_nattch;
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Leave a Reply to Antony043 Cancel reply

  • Thanks for the source code! It really helped me. Is it possible to have dynamic shared memory somehow? For example a shared vector or something like that?

Categories

Tags