Linux: Shared Memory

  • Shared memory allows two or more process to share a given region of memory created by another process. 
  • This is fastest form of IPC, because the data does not need to be copied between the client and the server. 
  • The trick in using shared memory is synchronizing the access to a given region among multiple processes.
  • If the server is placing data into the shared memory region, the client shouldn’t try to access the data until the server is done. 
  • Often Semaphores are used to synchronize shared memory access.
Advantages of Shared Memory:
 
Random Access
  • You can update a small piece in the middle of a data structure, rather than the entire structure 
Efficiency 
  • Unlike message queues and pipes, which copy data from the process into memory within the kernel, shared memory is directly accessed.
  • Shared memory resides in the user process memory, and is then shared among other processes.
Disadvantages of Shared Memory:
  • No automatic synchronization as in pipes or message queues (you have to provide any synchronization). Synchronize with semaphores or signals.
  • You must remember that pointers are only valid within a given process.
Creating Shared Memory:

        int shmget (key_t key, size_t size, int shmflg); 

   -key is either a number or the constant IPC_PRIVATE shmid is returned    -size is the size of the shared memory data 
   -shmflg is a rights mask (0666) OR’d with one of the following: 
             IPC_CREAT will create or attach 
             IPC_EXCL creates new or it will error if it exists.

Attaching to Shared Memory:

After obtaining a shmid from shmget(), you need to attach or map the shared memory segment to your data reference: 
      
         void * shmat(int shmid, void * shmaddr, int shmflg)          
         -shmid is the id returned from shmget() 
         -shmaddr is the shared memory segment address. Set this to NULL and  
              let the system handle it. 
         -shmflg is one of the following (usually 0):
                               SHM_RDONLY sets the segment readonly
                               SHM_RND sets page boundary access
                               SHM_SHARE_MMU set first available aligned address

dettaching to Shared Memory:

             int shmdt (void *shmaddr);

Shared Memory Control:
        
             int shmctl (int shmid, int cmd, struct shmid_ds * buf);

No comments:

Post a Comment