In: Computer Science
how to accept string from shared memory using c language ?
Inter Process Communication through shared memory is a concept where two or more process can access the common memory & communication is done via this shared memory where changes made by one process can be viewed by another process.
Steps:-
1. Server reads from the input file.
2. The server writes this data in a message using either a pipe,
fifo or message queue.
3. 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.
4. 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.
Some concepts used are:-
1. ftok(): is use to generate a unique key.
2. shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment.
3. shmat(): Before you can use a shared memory segment, you have to attach yourself to it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);
shmid is shared memory id. shmaddr specifies specific address to use but we should set it to zero and OS will automatically choose the address.
4. shmdt(): When you’re done with the shared memory segment,
your program should
detach itself from it using shmdt(). int shmdt(void *shmaddr);
5. shmctl(): when you detach from shared memory,it is not destroyed. So, to destroy shmctl() is used. shmctl(int shmid,IPC_RMID,NULL);
Program of Shared Memory for Writer Process:-
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
gets(str);
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
Program of Shared Memory for Reader Process:-
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}