We will invoke the ftok function to generate an IPC key. The filename and ID that are supplied for generating the key are sharedmem (any name) and a, respectively. The generated key is assigned to the key variable. Thereafter, we will 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 earlier.
We will create the new memory segment with read and write permissions and assign the fetched shared memory identifier to the shmid variable. The shared memory segment is then attached to the first available address in the system. This is done so that we can access the text that was written in the shared memory segment through the previous program.
So, after the memory segment is attached to the address space, the segment's start address is assigned to the str variable. Now, we can read the content that's been written in the shared memory through the previous program in the current program. The content from the shared memory segment is read through the str string and displayed on screen.
Thereafter, the attached memory segment is detached from the address space. Finally, the shared memory identifier shmid is removed from the system and the shared memory segment is destroyed.
Let's use GCC to compile the writememory.c program, as follows:
$ gcc writememory.c -o writememory
If you get no errors or warnings, this means that the writememory.c program has compiled into an executable file, writememory.exe. Let's run this executable file:
$ ./writememory
Enter the string to be written in memory : Today it might rain
String written in memory: Today it might rain
Now, press Alt + F2 to open a second Terminal window. In this window, let's use GCC to compile the readmemory.c program, as follows:
$ gcc readmemory.c -o readmemory
If you get no errors or warnings, this means that the readmemory.c program has compiled into an executable file, readmemory.exe. Let's run this executable file:
$ ./readmemory
Data read from memory: Today it might rain
Voila! We've successfully communicated between processes using shared memory.