Hi,
Shared memory allows multiple processes to share a virtual memory space.
One process creates or allocates the shared memory space and defines
the size and access rights to that memory region.
The code for memory allocation consists of the following few lines...
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
...
int shmid;
...
if( ( shmid = shmget( KEY, SIZE, SHMFLAG ) ) == -1 )
{
do some error handling, errno is set
}
the first argument KEY specifies the the key to use for the memory segment. It may either be the value IPC_PRIVATE when a new segment shall be created or it is a non zero value identifying the memory segment.
SIZE is the requested size of the memory segment (1 Byte to 1 MByte).
The SHMFLAG argument is used to set the IPC_CREAT flag and the
read/write permissions. Have a look in the man pages for further details
Once the shared memory segment is created it can be controlled via the function
status = shmctl( SHMID, CMD, struct shmid_ds *BUFFER );
The first argument SHMID is a shared memory segment identifier returned by the shmget function call.
With the second argument we can define a command to be executed
The third argument finally is a reference to the shmid_ds structure
(see <sys/shm.h> for details).
Valid operations are
IPC_STAT for returning the current values of the shmid_ds structure,
IPC_SET for modifying structure members
IPC_RMID for the removal of the system data structure for the referenced shmid
SHM_LOCK for locking the memory segment
SHM_UNLOCK for unlocking sth memory segment
The shared memory segment can be mapped into the data segment of a process. This operation is performed by the
void *shmat( SHMID, void *shmaddr, int shmflag ); function call
obviously shmid is the identifier of the shared memory segment, shmaddr
is used to assign the location of the memory segment. If shmaddr is not zero then the system will take this addrss as the attachments address for the shared memory. If shmaddr = 0 the system will pick the attachment address (not really recommended).
With the third argument you can specify the the access permissions .
The status = shmdt( void *shmaddr ); function call is used to detach the calling process's data segement from the shared memory region.
It is the programmers task to pass the shmid to the processes accessing the common shared memory area. Think about shmid as an additional argument when forking new processes; other methods are lockfiles etc.
Enjoy
Martin