Interprocess communication learning summary

  

To use shared memory, there should be the following steps: 1. Open a shared memory shmget () 2. Allow the process to use a shared memory shmat () 3. Write /read 4 It is forbidden to use this shared memory shmdt(). 5. Delete this shared memory shmctl() or ipcrm

shared memory under the command line. It is the most useful interprocess communication method and the fastest. IPC form. The shared memory of two different processes A and B means that the same physical memory is mapped to the process address space of each of processes A and B. Process A can immediately see that Process B updates the data in shared memory, and vice versa. Since multiple processes share the same memory area, some sort of synchronization mechanism is necessary, and both the mutex and the semaphore can be used.

One: Concepts

An obvious benefit of using shared memory communication is efficiency, because processes can read and write directly to memory without requiring any copy of the data. For communication methods like pipe and message queue, you need to copy data four times in the kernel and user space, while shared memory only copies data twice [1]: once from the input file to the shared memory area, and once from the shared Memory area to output file. In fact, when sharing memory between processes, it is not always possible to read and write a small amount of data and then unmap. When there is new communication, re-establish the shared memory area. Instead, the shared area is maintained until the communication is completed, so that the data content is always stored in the shared memory and the file is not written back. Content in shared memory is often written back to the file when it is unmapped. Therefore, the communication method using shared memory is very efficient. The Linux 2.2.x kernel supports multiple shared memory methods, such as mmap() system calls, Posix shared memory, and system V shared memory. Linux distributions such as Redhat 8.0 support mmap () system calls and system V shared memory, but have not implemented Posix shared memory, this article will mainly introduce the principle and application of the system V shared memory API.

System V shared memory refers to all shared data in the shared memory region (IPC shared memory region), any process that wants to access the data must add a memory area in the address space of the process Used to map physical memory pages that hold shared data.

System V implements shared memory communication between processes by mapping files in the special file system shm. That is to say, each shared memory area corresponds to a file in the special file system shm (this is linked by the shmid_kernel structure), which will be explained later.

The data that needs to be shared between processes is placed in a place called IPC shared memory area. All processes that need to access the shared area must map the shared area to the address space of the process. System V shared memory obtains or creates an IPC shared memory area via shmget and returns the corresponding identifier. The kernel guarantees that shmget obtains or creates a shared memory area, initializes the corresponding shmid_kernel structure of the shared memory area, and creates and opens a file with the same name in the special file system shm, and establishes the corresponding file in the memory. Dentry and inode structure, the newly opened file does not belong to any process (any process can access the shared memory area). All of this is done by the system calling 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, it is a bridge of storage management and file system, defined as follows: struct shmid_kernel{struct kern_ipc_perm shm_perm; Struct file *shm_file;int id;unsigned long shm_nattch;unsigned long shm_segsz;time_t shm_atim;time_t shm_dtim;time_t shm_ctim;pid_t shm_cprid;pid_t shm_lprid;}; The most important field in the structure should be shm_file, which stores the The address of the map file. Each shared memory area object corresponds to a file in the special file system shm. In general, files in the special file system shm cannot be accessed by read(), write(), etc., when the shared memory is used. After the file is mapped to the process address space, it can be accessed directly by accessing the memory.

As with message queues and semaphores, the kernel maintains all shared memory regions in the system via the data structure struct ipc_ids shm_ids. The shm_ids.entries variable in the above image points to an array of ipc_id structures, and each ipc_id structure array has a pointer to the kern_ipc_perm structure. Readers should be familiar with this. For the system V shared memory area, the host of kern_ipc_perm is shmid_kernel structure, and shmid_kernel is used to describe a shared memory area, so that the kernel can control all shared areas in the system. At the same time, the file type pointer shm_file of the shmid_kernel structure points to the corresponding file in the file system shm, so that the shared memory area is associated with the file in the shm file system. After creating a shared memory area, it is also mapped to the process address space, and the system calls shmat() to do this. Since a file of the same name in the file system shm has been created corresponding to the shared memory area when shmget() is called, the process of calling shmat() is equivalent to mapping the file process of the same name in the file system shm.

Two: System V shared memory API

For system V shared memory, there are mainly the following APIs: shmget(), shmat(), shmdt(), and shmctl(). #include <sys/ipc.h>#include <sys/shm.h>

shmget() is used to obtain the ID of the shared memory area. If the specified shared area does not exist, create the corresponding area. . 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 unmap the process from the shared memory area. Shmctl implements control operations on shared memory regions.

Three: Instances

An example of two processes sharing memory communication through system V.

#include <sys/ipc.h>#include <sys/shm.h>#include <sys/types.h>#include <unistd.h>typedef struct{char name[ ,null,null,3],4];int age;} people;//The process address space opens up a memory area for shared memory mapping main(int argc, char** argv){int shm_id,i;key_t key;char temp;people * P_map;char* name = "/dev/shm/myshm2";key = ftok(name,0);//The previous ones were 'a'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);//map to process address space memory temp='a';for (i = 0; i < 10; i++) {temp+=1;memcpy((*(p_map+i)).name,&temp,1);//Write to shared memory (that is, write in the mapped memory of the process),

(*(p_map+i)).age=20+i;//(*(p_map+i)) .name is equivalent to (p_map+i)->name }if(shmdt(p_map)==-1)//Unmap perror(" deta Ch error ");}#include <sys/ipc.h>#include <sys/shm.h>#include <sys/types.h>#include <unistd.h>typedef struct{char name [4];int age;} people;main(int argc, char** argv){int shm_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<10;i++){printf( "name:%s\ ",(*(p_map+i)).name );//for sharing Memory read operation (that is, the mapped memory of the read process) printf( "age %d\ ",(*(p_map+i)).age );}if(shmdt(p_map) == -1)perror(" ; detach error ");}

testwrite.cCreate a system V shared memory area, and write formatted data in it; testread.c access the same system V shared memory area, read out Format the data. Compile the two programs into testwrite and testread respectively, and execute ./testwrite and ./testread. The result of ./testread is as follows: name: b age 20; name: c age 21; name: d age 22; name: e age 23; name: f age 24; name: g age 25; name: h age 26; name: I age 27; name: j age 28; name: k age 29;

Copyright © Windows knowledge All Rights Reserved