Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
System call used for shared memory 
2.1.
shmget()
2.2.
2. shmat()
2.3.
3. shmdt()
2.4.
4. shmctl()
2.5.
5. ftok()
3.
Code Implementation of Shared Memory for Writer Process
4.
 Code Implementation of Shared Memory for Reader Process
5.
Frequently Asked Questions
5.1.
How do I set a shared memory area for IPC?
5.2.
What is the advantage of shared memory IPC?
5.3.
What are the system calls used in IPC through shared memory?
5.4.
What is ‘shared memory’ in inter-process communication?
5.5.
Which function is used to attach the process to the shared memory?
5.6.
Which function is used to deallocate the shared memory segment?
5.7.
What are the benefits of using shared memory for IPC?
6.
Conclusion
Last Updated: Jul 2, 2024
Medium

IPC through Shared Memory

Author ANKIT KUMAR
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM
Operating Systems

Introduction

We know that two main methods for inter-process communication are shared memory and message passing. In the shared memory method, two processes communicate with each other using common shared memory. The shared memory is present in the address space of the communicating process.

Unlike the message passing technique, in shared memory, only two copies of the data are created. The first copy is from the input file into the shared memory, and the second copy is from the shared memory to the output file.

In this article, we will see how this method is technically implemented. We shall analyze the various system calls used in the shared memory method for inter-process communication.

Properties of shared memory:

  • It is a comparatively faster method than the message queue.
  • It does not require an extra kernel buffer.
  • Race condition can be possible.
  • It is a relatively safe method. 

Also see, Introduction to Process Synchronisation, Multiprogramming vs Multitasking

System call used for shared memory 

shmget()

It is used to obtain access to a shared memory segment by a process involved in the inter-process communication. A process allocates a shared memory by using the shmget() function.

Syntax:

#include <sys/shm.h>

int shmget (key_t key, size_t size, int shmflg)

  • Key: It is an access value associated with the shared memory segment
  • Size: It represents the size (number of bytes) that has been requested for the shared memory segment.

Upon successful allocation of the shared memory segment, then shmget() returns an identifier. It returns -1 in case of an error.

2. shmat()

It is used to attach the shared memory segments. Once the shared memory segment is created by a process, the other process that wants to access that segment for inter-process communication should attach itself to the segment. This is done with the help of shmat(). In order to access the shared memory segment, the process must attach to the address space of the process that created the segment.

Syntax: 

#include <sys/shm.h>

void *shmat (int shm_id, const void *shm_addr, int shmflg);

  • First parameter: The first parameter is the shm_id which is the shared memory id. It is the identifier that is returned by the shmget().
  • Second parameter: The second parameter represents the address at which the segment is supposed to be attached to the current process. It is always a NULL pointer. It is kept NULL so that the system can choose the address at which the memory is available.
  • Third parameter: The third parameter represents the flag value.

If the shmat() system call is successful, it will return the address of the attached memory segment. In case there is an error, it will return -1.

3. shmdt()

This function call is used to detach memory segments. When the work of a process completes, i.e., it has completed sharing the information from the shared memory segment; it must be detached from the shared memory segment. The shmdt() function will detach the shared memory segment from the current process.

Syntax:

#include <sys/shm.h>

int shmdt (const void *shm_addr)

  • The shmdt() takes the pointer to the address that is returned by the shmget() as the parameter.

After successfully detaching the process from the shared memory segment, it returns 0. In case of an error, it returns -1.

4. shmctl()

Once the use of the shared memory is over, it is important to deallocate it. It should not unnecessarily use any memory. So to deallocate the shared memory segment, the shmctl() function call is used. The shmctl() function returns the information about a shared memory segment, and it can be modified also.

Syntax: 

#include <sys/shm.h>

int shmctl (int shm_id, int command, struct shmid_ds *buf);

  • First parameter: The first parameter shm_id is an identifier that is returned by the shmget() function.
  • Second parameter: It represents the various command values such as IPC_STAT, IPC_SET, IPC_RMID.
  • Third parameter: The third parameter, *buf, is a pointer to the structure of type struct shmid_ds, which is defined in <sys/shm.h> containing the modes and permissions for the shared memory.

5. ftok()

Purpose: ftok() generates a unique key for IPC (Inter-Process Communication) mechanisms like shared memory, semaphores, and message queues.

Parameters: It takes a file path (pathname) and a project identifier (proj_id) as input.

Key Generation: The key is based on the inode number of the file specified by pathname and the least significant 8 bits of proj_id.

Return Value: Returns a key_t key on success, -1 on failure (with errno set accordingly).

Usage: Essential for identifying and accessing IPC resources tied to a specific file, ensuring efficient communication between processes in Unix-like operating systems

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Code Implementation of Shared Memory for Writer Process

  • Code for the process of writing in the shared memory
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
main() {
   key_t my_key = ftok("shmfile",65); // used to generate unique key
   int shmid = shmget(my_key,1024,0666|IPC_CREAT); // It returns an id in shmid
   char *str = (char*) shmat(shmid,(void*)0,0); // shmat to attach to shared memory
   cout<<"Write Data : ";
   fgets(str, 50, stdin);
   printf("Data written in memory: %s\n",str);
   shmdt(str); // to detach from the shared memory
}

 Code Implementation of Shared Memory for Reader Process

  • Code for the process reading from the shared memory
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
main() {
   key_t my_key = ftok("shmfile",65); //used to generate unique key
   int shmid = shmget(my_key,1024,0666|IPC_CREAT); // shmget returns an id in shmid
   char *str = (char*) shmat(shmid,(void*)0,0); // to attach the process to shared memory
   printf("Data read from memory: %s\n",str);
   shmdt(str);
   shmctl(shmid,IPC_RMID,NULL); // to deallocate the shared memory

}

You can also read about the memory hierarchy, Open Source Operating System

Frequently Asked Questions

How do I set a shared memory area for IPC?

Allocate with shmget(), attach with shmat(), and manage with shmctl().

What is the advantage of shared memory IPC?

Offers fast communication between processes by allowing them to share data directly in memory, avoiding overhead of copying data.

What are the system calls used in IPC through shared memory?

shmget(), shmat(), shmdt(), shmctl()

What is ‘shared memory’ in inter-process communication?

It is a technique through which processes communicate using a shared memory that is attached to their address space.

Which function is used to attach the process to the shared memory?

shmat()

Which function is used to deallocate the shared memory segment?

shmctl()

What are the benefits of using shared memory for IPC?

It is fast and safe.

Conclusion

  • Two main methods for inter-process communication are shared memory and message passing.
  • In the shared memory method, two processes communicate with each other using common shared memory.
  • shmget(), shmat(), shmdt(), shmctl() are the commonly used system calls in the shared memory method.
  • ftok() is another system call that generates a unique id.
  • shmat() is used to attach the shared memory segments.
  • shmdt() is used to detach memory segments. 
  • To deallocate the shared memory segment, the shmctl() function call is used.


Recommended Readings: 


Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy learning!

Live masterclass