- Invoke the ftok function to generate an IPC key. The filename and ID that are supplied should be the same as those in the program for writing content into shared memory.
- Invoke the shmget function to allocate a shared memory segment. The size that's specified for the allocated memory segment is 1024 and is associated with the IPC key that was generated in step 1. Create the memory segment with read and write permissions.
- Attach the shared memory segment to the first available address in the system.
- The content from the shared memory segment is read and displayed on screen.
- The attached memory segment is detached from the address space.
- The shared memory identifier is removed from the system, followed by destroying the shared memory segment.
The readmemory.c program for reading data from shared memory is as follows:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int shmid;
char * str;
key_t key = ftok("sharedmem",'a');
if ((shmid = shmget(key, 1024,0666|IPC_CREAT)) < 0) {
perror("shmget");
exit(1);
}
if ((str = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
printf("Data read from memory: %s\n",str);
shmdt(str);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
Let's go behind the scenes.