IPC through shared memory
Last Updated :
19 Oct, 2023
Inter Process Communication through shared memory is a concept where two or more process can access the common memory and communication is done via this shared memory where changes made by one process can be viewed by another process.
The problem with pipes, fifo and message queue – is that for two process to exchange information. The information has to go through the kernel.
- Server reads from the input file.
- The server writes this data in a message using either a pipe, fifo or message queue.
- The client reads the data from the IPC channel,again requiring the data to be copied from kernel’s IPC buffer to the client’s buffer.
- Finally, the data is copied from the client’s buffer.
A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into shared memory and from shared memory to the output file.
Used System Calls
The system calls that are used in the program are:
Function
|
Signature
|
Description |
ftok() |
key_t ftok()
|
It is used to generate a unique key. |
shmget() |
int shmget(key_t key,size_t size, int shmflg);
|
Upon successful completion, shmget() returns an identifier for the shared memory segment. |
shmat() |
void *shmat(int shmid ,void *shmaddr ,int shmflg);
|
Before you can use a shared memory segment, you have to attach yourself to it using shmat(). Here, shmid is a shared memory ID and shmaddr specifies the specific address to use but we should set it to zero and OS will automatically choose the address. |
shmdt() |
int shmdt(void *shmaddr);
|
When you’re done with the shared memory segment, your program should detach itself from it using shmdt(). |
shmctl() |
shmctl(int shmid,IPC_RMID,NULL);
|
When you detach from shared memory, it is not destroyed. So, to destroy shmctl() is used. |
Shared Memory for Writer Process
CPP
#include <iostream>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;
int main()
{
key_t key = ftok( "shmfile" , 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char * str = ( char *)shmat(shmid, ( void *)0, 0);
cout << "Write Data : " ;
cin.getline(str, 1024);
cout << "Data written in memory: " << str << endl;
shmdt(str);
return 0;
}
|
Shared Memory for Reader Process
CPP
#include <iostream>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;
int main()
{
key_t key = ftok( "shmfile" , 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char * str = ( char *)shmat(shmid, ( void *)0, 0);
cout << "Data read from memory:" << str;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
|
Output
Share your thoughts in the comments
Please Login to comment...