In: Computer Science
A) Declare 'buffer as string.'a' and 'b' as integers.Set the value for 'a' is 100.
B) Write a program to find the address location for buffer 'a' and 'b' and three segments in the process memory.
thank you.
pls answer with proper explaination
Inter-Process Communication through shared memory is a concept where two or more processes 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 processes to exchange information. The information has to go through the kernel.
A total of four copies of data are required (2 reads and 2 writes). 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.
SYSTEM CALLS USED ARE:
ftok(): is used to generate a unique key.
shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment.
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.
shmdt(): When you’re done with the shared
memory segment, your program should
detach itself from it using shmdt(). int shmdt(void *shmaddr);
shmctl(): when you detach from shared memory,
it is not destroyed. So, to destroy
shmctl() is used. shmctl(int shmid,IPC_RMID,NULL);
#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("a",100);
// shmget returns an identifier in shmid
int a = shmget(key,100|IPC_CREAT);
// shmat to attach to shared memory
char *b = (char*) shmat(a,(void*)0,0);
cout<<"Write Data : ";
gets(b);
printf("Data written in memory: %s\n",b);
//detach from shared memory
shmdt(b);
return 0;
}