Basic Working of Shared Memory:
The sender sends the data and the receiver receives the data, by applying the following steps:
Sender:
1) Create the shared segment
2) Attach to it
3) Write some content into it.
4) To Copy the data into a shared segment
Receiver:
1) Attach itself to the shared segment
2) Read the value written by Program 1
Function's Required:
Available in:
#include<sys/ipc.h>
#include<sys/shm.h>
Prototype: int shmget(key_t key, size_t size,int shmflg);
where,
key_t : sharedmemory id,
size_t: in kb
shmflg: read/write permission
return: integer shmid (Valid Identifier) that we used at shmat()
Available in:
#include<sys/shm.h>
#include<sys/types.h>
Prototype: void *shmat(int shmid,const void *shmaddr,int shmflg);
where,
shmid: The value return by shmget() function.
shmaddr: Where to attach the shared segment in calling segment ,
NULL: System will automatically attach appropriate address space
shmflg: If you have given address specifically then use SHM_RND
If shmaddr is NULL then, shmflg default value is 0
return: void pointer
Program Sender.c :
#include<stdio.h> #include<stdlib.h> #include<sys/ipc.h> #include<sys/shm.h> #include<sys/types.h> #include<string.h> #include<unistd.h>
int main() { int i; // to print where the shared segment gets attach to the process address space void *shared_memory; // buffer it is used to write the data into shared memory by the user char buff[100]; int shmid; // creates shared memory segment with key 2345 (any number that you want to assign to // the shared segment), having size 1024 bytes. // IPC_CREAT is used to create the shared segment if it does not exist. // 0666 (read and write to user,group and other) are the permissions on the shared segment shmid=shmget((key_t)2345, 1024, 0666|IPC_CREAT); printf("Key of shared memory is %d\n",shmid); //process attached to shared memory segment shared_memory=shmat(shmid,NULL,0); //this prints the address where the segment is attached with this process printf("Process attached at %p\n",shared_memory); printf("Enter some data to write to shared memory\n"); read(0,buff,100); //get some input from user //data written to shared memory strcpy(shared_memory,buff); printf("You wrote : %s\n",(char *)shared_memory); }
Program Receiver.c :
#include<stdio.h> #include<stdlib.h> #include<sys/ipc.h> #include<sys/shm.h> #include<sys/types.h> int main() { int i; void *shared_memory; char buff[100]; int shmid; // to get shmid which will be require as parameter to shmat() function shmid=shmget((key_t)2345, 1024, 0666); printf("Key of shared memory is %d\n",shmid); //process attached to shared memory segment shared_memory=shmat(shmid,NULL,0); printf("Process attached at %p\n",shared_memory); printf("Data read from shared memory is : %s\n",(char *)shared_memory); }
Output: