Deep understanding of shared memory for interprocess communication

Source: Internet
Author: User

Shared memory can be said to be the most useful inter-process communication and the fastest form of IPC. is designed for inefficient operation of other communication mechanisms. Two different processes A, B shared memory means that the same piece of physical memory is mapped to the respective process address space of process A and B. Process A can instantly see that process B updates the data in shared memory, and vice versa. Because multiple processes share the same block of memory, there is a need for some kind of synchronization mechanism, both mutexes and semaphores.

One obvious benefit of using shared memory communication is that it is efficient because the process can read and write directly to the memory without requiring any copy of the data. For communication methods such as pipelines and message queues, four copies of the data are required in the kernel and user space, while shared memory copies only two data [1]: One from the input file to the shared memory area, and the other from the shared memory area to the output file. In fact, when you share memory between processes, you do not always have to read and write small amounts of data, and then re-establish the shared memory area when there is new communication. Instead, the shared area is maintained until the communication is complete, so that the data content is kept in shared memory and is not written back to the file. Content in shared memory is often written back to a file when it is de-mapped. Therefore, the use of shared memory communication mode is very efficient.

System V Shared Memory principle

The data that needs to be shared between processes is placed in a region called IPC shared memory, and all processes that need to access the shared zone map the shared area to the address space of the process. System V shared memory obtains or creates an IPC shared memory region through Shmget, and returns the appropriate identifier. While the kernel guarantees that shmget obtains or creates a shared memory area, initializes the corresponding Shmid_kernel structure of the shared memory area, it also creates and opens a file of the same name in the special file system SHM, and establishes the corresponding dentry and inode structure of the file in memory. The newly opened file does not belong to any one process (any process can access the shared memory area). All of this is done by the system call Shmget.

Note: Each shared memory area has a control structure struct Shmid_kernel,shmid_kernel is a very important data structure in the shared memory area, which is a bridge between storage management and file system, which is defined as follows:

structShmid_kernel/*private to the kernel*/{        structKern_ipc_perm Shm_perm;/*Operation permission Structure*/    structFile *shm_file;/*pointer in kernel*/unsignedLongShm_nattch;/*Number of current attaches*/unsignedLongShm_segsz;/*size of segment in bytes*/time_t Shm_atim;/*Last-attach Time*/time_t Shm_dtim;/*Last-detach Time*/time_t Shm_ctim;/*Last-change Time*/pid_t Shm_cprid;/*pid of creator*/pid_t Shm_lprid;/*pid of Last Shmop ()*/};

System V Shared Memory API
Header file:
#include <sys/ipc.h>
    #include <sys/shm.h>

Shmget () is used to obtain the ID of the shared memory area, and if the specified shared area does not exist, the corresponding zone is created. Shmat () maps the shared memory area to the address space of the calling process so that the process can easily access the shared area. The SHMDT () call is used to dismiss a process's mapping to a shared memory region. SHMCTL implements control operations on shared memory areas.

System V Shared memory limit

In the/proc/sys/kernel/directory, the limit of System V shared memory is recorded, such as the maximum number of bytes in a shared memory area Shmmax, the system-wide maximum number of shared memory area identifiers Shmmni, etc., can be adjusted manually, but this is not recommended.

System V Shared Memory example
/** * * * testwrite.c *******/#include<sys/ipc.h>#include<sys/shm.h>#include<sys/types.h>#include<unistd.h>typedefstruct{    Charname[4]; intAge ;} People;main (intargcChar**argv) {    intShm_id,i;    key_t key; Chartemp; People*P_map; Char* Name ="/dev/shm/myshm2"; Key= Ftok (Name,0); if(key==-1) perror ("Ftok Error"); shm_id=shmget (Key,4096, ipc_creat); if(shm_id==-1) {perror ("Shmget Error"); return; } P_map= (people*) Shmat (Shm_id,null,0); Temp='a';  for(i =0;i<Ten; i++) {Temp+=1; memcpy ((* (P_map+i)). Name,&temp,1); (* (P_map+i)). age= -+i; }    if(SHMDT (P_map) ==-1) perror ("Detach Error");}/********** testread.c ************/#include<sys/ipc.h>#include<sys/shm.h>#include<sys/types.h>#include<unistd.h>typedefstruct{    Charname[4]; intAge ;} People;main (intargcChar**argv) {    intShm_id,i;    key_t key; People*P_map; Char* Name ="/dev/shm/myshm2"; Key= Ftok (Name,0); if(Key = =-1) perror ("Ftok Error"); shm_id= Shmget (Key,4096, ipc_creat); if(shm_id = =-1) {perror ("Shmget Error"); return; } P_map= (people*) Shmat (Shm_id,null,0);  for(i =0;i<Ten; i++) {printf ("name:%s\n", (* (p_map+i)).    name); printf ("Age %d\n", (* (p_map+i)).    Age); }    if(SHMDT (p_map) = =-1) perror ("Detach Error");}
View Code

  

Deep understanding of shared memory for interprocess communication

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.