Shared Memory
Shared memory is memory that may be simultaneously accessed by multiple programs with an intent to provide communication among them or avoid redundant copies. Shared memory is an efficient means of passing data between processes as shown in figure below.

Using shared Library in C
If you use the following functions in your program, you should link your program with -lrt.
If a process wants to access shared memory, it should (using POSIX API):
Create, or gain access to, a shared memory object.
Map a shared memory object into its address space.
Do operations on shared memory (read, write, update).
Delete mappings of the shared memory object.
Finally, destroy a shared memory object when no reference to it remain open.
Shared Memory: Example
Here are two programs, namely producer and consumer. Producer will write something to shared memory; and the consumer will read from it and remove it.
Producer:
Consumer:
Compile:
$ gcc -o prod shm-posix-producer.c -lrt

$ gcc -o con shm-posix-consumer.c -lrt

Actually a shared memory can be found under the/dev/shm folder as a file.

Reference:
http://www.cse.psu.edu/~deh25/cmpsc473/notes/OSC/Processes/shm.html
Last updated
Was this helpful?