Karachi   ->   Sweden   ->   Karachi, again   ->   Dubai   ->   Bahrain   ->   Karachi, once more   ->   London and Leeds

Thursday, December 23, 2010

Linux Shared Memory Cheat Sheet

A quick cheat sheet of how to create, access, detach and destroy shared memory in Linux using C language is provided below. There is another way of accessing shared memory, i.e., by using POSIX functions for the same; that is not discussed here.

Linux Shared Memory Life Cycle

Header Files for Shared Memory


You need to include the following header files
sys/shm.h and sys/stat.h

Allocate shared memory


int segmentId = shmat (IPC_PRIVATE, size, flags);
where size is an integer telling the size required in bytes
Flags is Oring of things like IPC_CREAT | IPC_EXCL | SI_IRUSR | SI_IWUSR(create an exclusive shared memory that can be read from and written to by the current user)

Attach to shared memory


char *sharedMem = (char *) shmget (segmentId, 0, 0);

Detatch shared memory


shmdt (sharedMem);

Deallocate shared memory


shmctl (segmentId, IPC_RMID, 0);


Advanced Usage


If you want more control of the shared memory, you need to know shmctl better.

Determine the segment size


You need a structure to hold segment information. Declare like this
struct shmid_ds buffer
and then use like this
shmctl (segmentId, IPC_STAT, &buffer);
int segmentSize = buffer.shm_segsz;