In this blog we will learn how to use shared memory for interprocess communication in Linux. After reading this tutorial blog ,we will learn What is shared memory in interprocess communication? How can two processes communicate with one another? How does shared memory work in Linux? Why Shared memory is faster?

What is shared memory in interprocess communication?

Shared memory is a common memory location where two or more processes can access this common memory location. one process can write something and another process can read from shared memory.

How to use shared memory for interprocess communication

Linux system provides  some simple APIs to create ,control and access shared memory. these APIs are

shget() , this api allocates a shared memory segment.

shmat() , this api attach shared memory in calling process.

shmdt() , this api detach memory segment, this is done after doing operation on shared memory segment.

shmctl() , int shmctl(int shmid, int cmd, struct shmid_ds *buf);

performs the control operation specified by cmd on the System V shared memory segment whose identifier is given in shmid. for example to remove allocated shared memory we case use

/* Deallocate the segment. */
shmctl (segment_id, IPC_RMID, 0);

/*
  sample.c , it will create shared memory
*/
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_ID 0x2304
#define SIZE_MEM 1024

int main ()

{
  int id;
  char* shared_memory;

  /* Allocate a shared memory segment.  */
  id = shmget (SHM_ID, SIZE_MEM, 0666 | IPC_CREAT);

  /* Attach the shared memory segment.  */
  printf("Shared memory segment ID is %d\n", id);

  shared_memory = (char*) shmat (id, 0, 0);

  /* Write a string to the shared memory segment.  */
  sprintf (shared_memory, "Hello, wikistack.");

  /* Detach the shared memory segment.  */
  shmdt (shared_memory);
  printf("Wrote Hello, wikistack to the segment\n");

}

Now let us read contents of shared memory created 

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>

#define SHM_ID 0x2304
#define SIZE_MEM 1024

int main ()

{
  int id;
  char* shared_memory;

  // shmget returns an identifier
  id = shmget(SHM_ID,SIZE_MEM,0666|IPC_CREAT);

  /* attach the shared memory segment, at a different address.  */
  shared_memory = (char*) shmat (id, (void*) 0x0, 0);

  printf ("shared memory attached at address %p\n", shared_memory);
  /* Print out the string from shared memory.  */
  printf ("the shared memory's content is:\n%s\n", shared_memory);
  /* Detach the shared memory segment.  */
  shmdt (shared_memory);

  return 0;

}


Related Contents to follow