Linux inter-process communication-shared memory

Source: Internet
Author: User

One, shared memory definition

( Baidu Encyclopedia ) shared memory refers to a large amount of memory that can be accessed by different central processors in a multiprocessor computer system. Because multiple CPUs require fast access to the memory, caching of the memory process is necessary. Once any cached data has been updated, shared memory needs to be updated immediately because other processors may also be accessible, otherwise different processors may be using separate data.

In a Linux system, shared memory allows a process or multiple processes to share a given store (shared memory). Memory that is shared between different processes is usually scheduled to the same physical address. Processes can connect the same piece of shared memory to their own address space, and all processes can access addresses in shared memory. Such a method is suitable for inter-process communication that is extremely complex in order of magnitude and data structure. However, this approach sacrifices the security of the system, so it is often mixed with other forms of interprocess communication.

Note: Shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from starting reading the shared memory until the first end of the operation. So we usually need to use other mechanisms to synchronize access to shared memory. For example: signal volume, mutual exclusion lock and so on.

Ii. Methods of Use

1. Create Shared memory

Call interface Shmget function

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

Parameters

Key: Identifies the value of the shared memory: If Ipc_private is used to create the private shared memory of the current process.

Size: Amount of shared memory

SHMFLG: Setting access permissions for shared memory

Return value: If the shared memory identifier is returned successfully, 1 is returned if it fails.

            int main ()              {                 int shmid=shmget (ipc_private,1024,0666);                 if (shmid<0)                  {                     printf ("error\n");                 }                 else                 {                     printf ("success\n");                 }                 return 0;             }

execution of the ipcs-m display at the command line, a memory area has been created successfully

The Nattch field shows the number of processes that have been attached to this memory area.   

2. Innuendo Shared memory

void* shmat (int shmid, char *shmaddr, int flag)

Parameters:

Shared memory identifier returned by the Shmid:shmget function

shmaddr: Specifies the address location of the shared memory connection to the current process

It is usually a null pointer

Represents an address that allows the system to select shared memory

Flag: Decide in what way to determine the address of the allusion (usually 0)

Return value: If successful, returns the shared memory mapped to the address in the process;

If it fails, it returns-1.

                int main ( Int args,char *argv[])                  {                     char *shmbuf=NULL;                     int shmid=0;                     if (ARG&GT;2)                      {                         shmid=atoi (argv[1]);           &nbsP;             shmbuf=shmat (shmid,0,0);                          if (Atoi (argv[2]==1)                          {                        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%s", Shmbud);                         }                          if (Atoi (argv[2]) ==2)                          {                              printf ("%s", Shmbuf);                         }         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SHMDT (SHMBUF) ;//detach the shared memory from the process                      }                     return 0;                 }



Note: The Nattch field shown by the IPCS-M command shows that there is a process attached to the shared memory.

3. Unlock Shared memory Mappings

The function shmdt is to detach the segment attached to SHMADDR from the address space of the calling process, which must be the address returned by Shmat.

int Shmdt (char *shmaddr);

The function call returned successfully to 0, and the failure returned-1.

4. Controlling Shared Memory

int shmctl (int shmid,int command,struct shmid_ds *buf);

Parameters:

Shmid is the shared memory identifier returned by the Shmget function.

Command: To take the action, it can take the following three values

Ipc_stat: Is the data in the SHMID_DS structure is set to the current associated value of shared memory, that is, the value of Shmid_ds is overwritten with the current associated value of shared memory.

Ipc_set: If the process has sufficient permissions, set the current association value of shared memory to the value given in the SHMID_DS structure

IPC_RMID: Deleting shared memory segments

Buf:buf is a struct pointer that points to the structure of shared memory mode and access rights.

SHMID_DS structure:

struct Shmid_ds {uid_t shm_perm.uid;                uid_t Shm_perm.gid;            mode_t Shm_perm.mode; };

5. Code Examples

             write to Shared memory:

#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/shm.h> #include < stdlib.h> #include <errno.h> #define  VALUE_SIZE 2048struct share_use_st{     int write_flag;//as a flag, non-0 is readable, 0 means writable     char value[value_size];// Record write and read text};int main () {   int run=1;   void *shm=null;    struct share_use_st *share=NULL;   char buf[VALUE_SIZE+1];    int shmid;   shmid=shmget (key_t) 123,sizeof (struct share_use_st), 0666| Ipc_creat);    if (shmid==-1)    {       printf ( "%s\n", Strerror (errno));        exit (exit_failure);   }    shm=shmat (shmid,null,0);    if (shm== (void *)-1)    {        priNTF ("%s\n", Strerror (errno));        exit (exit_failure);    }    printf ("\nmemory attached at %p\n", SHM);    //set up shared memory     share= (struct share_use_st*) shm;   while (run)    {       while (share->write_flag==1)       {           sleep (1);           printf ("waiting....\n");       }      printf ( "Enter some value:");       read (Stdin_fileno,buf,sizeof (BUF)-1);       strncpy (share->value,buf,value_size);       Share->write_flag=1;      if (strncmp (buf, "End", 3) ==0)        {          run=0;      }   }    if (SHMDT (SHM) ==-1)    {       printf ("%s\n" , Strerror (errno));        exit (exit_failure);   }    sleep (2);    return 0;}

        read from shared memory:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/shm.h> #include < Errno.h> #define  value_size 2048struct share_use_st{    int write_ flag;//as a flag, not 0 for readable, 0 for writable     char value[value_size];//record write and read text};int main (int  args,char *argv[]) {    int run=1;    void *shmbuf =null;//address of shared memory     struct share_use_st *shm;    int  shmid;//Shared Memory identifier     shmid=shmget ((key_t) 123,sizeof (struct share_use_st), 0666| Ipc_creat);     if (shmid==-1)     {         printf ("%s\n", Strerror (errno));         exit (EXIT_FAILURE);     }    //connect the shared memory to the address space of the current process     shmbuf=shmat (shmid , 0,0);    &nbsP;if (shmbuf== (void *)-1)     {        printf (" %s ", Strerror (errno));         exit (exit_failure);     }    printf ("\nmemory attach at %x", (int) SHM);     //Set Shared memory     shm= (struct share_use_st*) shmbuf;    shm-> Write_flag=0;    while (Run)     {         if (shm->write_flag!=0)         {             printf ("recv:%s\n", Shm->value);             sleep (rand ()%3);             //read data, set Write_flag to make shared memory writable              shm->write_flag=0;            //input end, exit loop              if (strncmp (Shm->value, "End", 3) ==0)                  run=0;         }        else         {            sleep (1);         }    }    // Detach shared memory from the current process     if (SHMDT (shmbuf) ==-1)     {         printf ("%s", Strerror (errno));         exit (exit _failure)     }    //Delete shared memory     if (Shmctl (Shmid,IPC _rmid,0) ==-1)     {        printf ("%s\n", Strerror (errno));         exit (exit_failure);     }    return exit_success ;}

Iii. Advantages and disadvantages of using shared memory

Advantages: The use of shared memory for interprocess communication is very convenient, the function interface is also simple, the data sharing also makes the process of communication with direct access to memory, eliminating the time of transmission, speed up the efficiency, but also do not want to call the Nameless pipeline communication process has a certain parent-child relationship.

Cons: Shared memory does not provide a mechanism for synchronization, which allows us to use shared memory often in other ways to synchronize issues between processes.

This article is from the "11182780" blog, please be sure to keep this source http://11192780.blog.51cto.com/11182780/1786081

Linux inter-process communication-shared memory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.