What is Shared Memory?
In the discussion of the fork() system call, we mentioned that a parent and its children have separate address spaces. While this would provide a more secured way of executing parent and children processes (because they will not interfere each other), they shared nothing and have no way to communicate with each other. A shared memory is an extra piece of memory that is attached to some address spaces for their owners to use. As a result, all of these processes share the same memory segment and have access to it. Consequently, race conditions may occur if memory accesses are not handled properly. The following figure shows two processes and their address spaces. The yellow rectangle is a shared memory attached to both address spaces and both process 1 and process 2 can have access to this shared memory as if the shared memory is part of its own address space. In some sense, the original address spaces is “extended” by attaching this shared memory.
Shared memory is a feature supported by UNIX System V, including Linux, SunOS and Solaris. One process must explicitly ask for an area, using a key, to be shared by other processes. This process will be called the server. All other processes, the clients, that know the shared area can access it. However, there is no protection to a shared memory and any process that knows it can access it freely. To protect a shared memory from being accessed at the same time by several processes, a synchronization protocol must be setup.
A shared memory segment is identified by a unique integer, the shared memory ID. The shared memory itself is described by a structure of type shmid_ds in header file sys/shm.h. To use this file, files sys/types.h and sys/ipc.h must be included. Therefore, your program should start with the following lines:
#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h>
A general scheme of using shared memory is the following:
- For a server, it should be started before any client. The server should perform the following tasks:
- Ask for a shared memory with a memory key and memorize the returned shared memory ID. This is performed by system call shmget().
- Attach this shared memory to the server’s address space with system call shmat().
- Initialize the shared memory, if necessary.
- Do something and wait for all clients’ completion.
- Detach the shared memory with system call shmdt().
- Remove the shared memory with system call shmctl().
- For the client part, the procedure is almost the same:
- Ask for a shared memory with the same memory key and memorize the returned shared memory ID.
- Attach this shared memory to the client’s address space.
- Use the memory.
- Detach all shared memory segments, if necessary.
- Exit.