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.
- 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().
- Controlling the shared memory using shmctl(), read below for complete description.
- 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.
shmctl() is used to alter the permissions and other characteristics of a shared memory segment. It is prototyped as follows:
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
The process must have an effective shmid of owner, creator or superuser to perform this command. The cmd argument is one of following control commands:
- SHM_LOCK
- -- Lock the specified shared memory segment in memory. The process must have the effective ID of superuser to perform this command.
- SHM_UNLOCK
- -- Unlock the shared memory segment. The process must have the effective ID of superuser to perform this command.
- IPC_STAT
- -- Return the status information contained in the control structure and place it in the buffer pointed to by buf. The process must have read permission on the segment to perform this command.
- IPC_SET
- -- Set the effective user and group identification and access permissions. The process must have an effective ID of owner, creator or superuser to perform this command.
- IPC_RMID
- -- Remove the shared memory segment.
No comments:
Post a Comment