当前位置:网站首页>Shared memory for interprocess communication
Shared memory for interprocess communication
2022-07-07 06:21:00 【*insist】
1.1 The introduction of shared memory
Shared memory is the fastest form of interprocess communication , By calling the system interface (shmget) Open up a piece of physical memory by the operating system , Then map to the process address space through the page table , Thus, users can use this memory , Two processes share a shared memory, and communication can be established through data interaction .
1.2 Create a schematic diagram between virtual memory and physical memory before and after shared memory
The connection between virtual memory and physical memory before shared memory is not created
- The connection between virtual address and physical memory is established through page table , All we see are physical memory mapped to the page table Virtual memory Not real physical memory ,
- among task_struct Is the data structure of the process ( This data structure is used to describe Managing the data structure is the management of the process ) mm_struct Is the data structure of the process address space
The connection between virtual memory and physical memory after creating shared memory
- After creating shared memory , After pointing the physical addresses of the two processes to the block of physical memory, the two processes can see the same resource , So as to realize the interaction of information , Achieve communication
2.1 The specific steps of communication through shared memory
- 1、 Request shared memory By function shmget() establish ( apply ) Out of shared memory
- 2、 Attach shared memory to the process address space By function shmat() Hook the of the process to the shared memory ; In essence, the process opens up a new virtual address space , By modifying the page table , Cancel the mapping relationship between the original virtual memory and physical memory , Will share memory ( This physical memory ) Establish a mapping relationship with the virtual memory of the process , Enable processes to use shared memory
- 3、 Disassociate shared memory By function shmdt() Disassociate shared memory ; Modify page table , Cancel the mapping relationship between shared memory and virtual memory , Restore the mapping relationship between the original physical memory and virtual memory of the process
4、 Free up shared memory By function int shmctl(int shmid, int cmd, struct shmid_ds *buf); Free up shared memory ; The life cycle of shared memory is automatically released with the kernel rather than with the end of the process ( Different from file ), If you don't release it after using it, the memory will be less and less , Memory leak , So remember to release the applied shared memory after using it
2.2 Instructions for viewing and deleting shared memory
2.2.1 View shared memory
// Input instruction
ipcs -m
2.2.2 Delete shared memory
// Input instruction
ipcrm -m +[shmid]//shmid It's shared memory id( user )
3.1 A simple demonstration of two processes communicating through the same shared memory
- Two processes share a shared memory , Then directly operate on the memory , It's like mallocc Use the same space that comes out , No need to call the system interface read write And so on to access this memory .
Specific code :
// The header file Include with ftok() Created key Required parameters Pathname and proj_id
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
#define pathname "/home/zh/nodeput/lesson23"
#define proj_id 0x36
#define SIZE 4096
-------------------------------------------
//client.c
#include"serve.h"
int main()
{
key_t key=ftok(pathname,proj_id);
if(key<0)
{
perror("ftok");
}
int shmid=shmget(key,SIZE,IPC_CREAT);// establish
char* mem=(char*)shmat(shmid,NULL,0);// Hook up
// Start communicating
int i=0;
while(1)
{
mem[i] = 'A'+ i;// Here is the direct use of the developed shared memory Assign a value to it Then another process can print it out
i++;
mem[i]='\0';
sleep(1);
}
shmdt(mem);// To relate
shmctl(shmid,IPC_RMID,NULL);// Release
return 0;
}
-------------------------
//serve.c
#include"serve.h"
int main()
{
key_t key=ftok(pathname,proj_id);// Generate key
if(key<0)
{
perror("ftok");
return 1;
}
int shmid= shmget(key,SIZE,IPC_CREAT|IPC_EXCL|0644);// adopt key Create shared memory
if(shmid<0)
{
perror("shmget");
return 2;
}
char* mem=(char*)shmat(shmid,NULL,0);// Attach shared memory
// Start communicating
while(1)
{
printf("client sent: %s\n",mem);
sleep(1);
}
shmdt(mem);// Disassociate shared memory
shmctl(shmid,IPC_RMID,NULL);// Free up shared memory
return 0;
}
3.1.1 A few points to be noted :
- 1、*key_t ftok(const char pathname,int proj_id)** The first parameter of the function is a path that must exist , It can be a file or a directory
- 2、 The path must exist ,ftok Just according to the documents inode Uniqueness in the system to take a value , It has nothing to do with the permissions of the file
- 3、proj_id Yes, according to your own agreement , Set at will . This number , Some call it project ID stay UNIX On the system , It's going to be theta 1 To 255,8 A bit ,2 Bytes
3.1.2 Introduction to the parameter return value of several functions
1. Create shared memory function
int shmget(key_t key,size_t size,int shmflg)
The first parameter :key key It's through ftok() Functions are based on pathname and proj_id A value created with a unique mapping relationship , Help the operating system to identify a piece of shared memory
The second parameter :size size Is the size of the shared memory we want to create , The memory we see is actually virtual memory , Physical memory is mapped out through the page table , Always mention mapping , But how does the computer map the virtual address space to the real physical memory ? So that's the point Memory segmentation and paging mode 了 This conversion process has operating system and CPU Joint completion . The operating system is CPU Set the page table CPU adopt MMU The unit performs address translation To put it simply , It is to divide the linear address space into one by one 4k Of ( Almost all PC All operations on use 4KB The size of the page ) Logical page , Divide the memory pages into fixed size physical pages in the same way 4kb,4096 byte , In order to make better use of memory size Alignment is best 4096 That is to say, it is better to set it to 4096 Integer multiple
The third parameter :shmflg It is mainly related to some signs , Include IPC_CEREAT and IPC_EXCL, These two are with open() Of O_CREAT and O_EXCL similar .
- Instructions :
- 1、 If it is IPC_CREAT Used alone is if the function corresponds to key If the shared memory of does not exist, create and return the shared memory of this block shmid If the shared memory of this block already exists, it will directly return its corresponding shmid IPC_CREAT Use alone shmget() The function call is bound to succeed , Or return the shared memory that already exists shmid Or return the newly created shared memory shmid
- 2、 If it is IPC_CREAT and IPC_EXCL Use together is to create and return the corresponding God when and only when the block shared memory does not exist shmid, Otherwise it will return -1
- 3、IPC_EXCL It doesn't make much sense to use the logo alone Only and IPC_CREAT Only when used together can it play its role , It can ensure that the successfully created shared memory must be newly created , Instead of existing .
- 4、 Specify for the user's read and write permissions SHM_R and SHM_W(SHM_R>3) and (SHM_W>3) Is a set of read and write permissions ,(SHM_R>6) and (SHM_W>6) Is the global read and write permission
2. Attach shared memory function
**void shmat(int shmid, const void shmaddr, int shmflg);
- The first parameter :shmid Namely shmget Create a good shared memory shmid( An integer identifier ), You can release the corresponding shared memory through this identifier
- The second parameter :shmaddr Is the designated address , If NULL Then the operating system automatically selects an appropriate address ; If it is not empty and is not specified SHM_RND, Then this paragraph links to shmaddr On the specified address , If shmaddr Not empty and specifies SHM_RND Then this segment is connected to shmaddr -(shmaddr mod SHMLAB) On the address indicated .SHM_RND Command means rounding ,SHMLAB It means multiple of low boundary address , It's always 2 Power of . The expression is to take the address down to the nearest SHMLAB Multiple . Unless you plan to run the application on only one hardware ( This is unlikely nowadays ), Otherwise, do not specify the address to which the shared segment is connected . Therefore, it is generally necessary to specify shmaddr by 0, So that the kernel can choose the address
- The third parameter :shmflg If it is 0 It's read-write mode ,SHM_RD0NLY It's read-only mode
3. To associate shared memory functions
**void shmat(int shmid, const void shmaddr, int shmflg)
- The first parameter :shmid Namely shmget Create a good shared memory shmid( An integer identifier ), You can release the corresponding shared memory through this identifier
- The second and third parameters are the same as the above shmat() identical
4. Free shared memory function
*int shmctl(int shmid, int cmd, struct shmid_ds buf)
- The first parameter : Identifier of shared memory
- The second parameter : Operation command Yes IPC_STAT、IPC_SET、IPC_RMID
- IPC_STAT Is to check the status of shared memory , Put the shared memory shmid_ds The structure is copied to buf in
- IPC_SET Is to change the state of shared memory , hold buf Referred to shmid_ds The structure of the uid、gid、mode Copy to shared memory shmid Within the structure
- IPC_RMID Is to free this shared memory
- The third parameter :buf Management structure of shared memory , Type of structure
- Return value : success 0 error -1
4.1 Comparison between shared memory communication and pipeline communication
1. Shared memory communication copies data less times , Fast
Shared memory can be used directly after it is created , It's like malloc Open up the same space , There is no need to call another function to access this memory
When communicating with the pipeline, you need to call the system interface after creating the pipeline read() and write() To access the pipeline file , In this way, there is data copy operation between buffers , Thus, the efficiency becomes low
2. The pipeline has its own synchronization and mutual exclusion mechanism , Shared memory does not
Having studied pipelines, we know that pipelines have their own synchronization and mutual exclusion mechanisms , Reading and writing cannot be done at the same time . But shared memory does not have this mechanism , This makes it possible to read and write data at the same time , To achieve a mechanism similar to synchronization and mutual exclusion, locks or semaphores are needed
边栏推荐
- c面试 加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。
- C语言整理(待更新)
- 直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级
- Sequential storage of stacks
- Cf:c. column swapping [sort + simulate]
- 职场经历反馈给初入职场的程序员
- c语言(结构体)定义一个User结构体,含以下字段:
- Check point: the core element for enterprises to deploy zero trust network (ztna)
- JVM命令之 jstat:查看JVM统计信息
- Several key steps of software testing, you need to know
猜你喜欢
tkinter窗口选择pcd文件并显示点云(open3d)
Check point: the core element for enterprises to deploy zero trust network (ztna)
CloudCompare-点对选取
When we talk about immutable infrastructure, what are we talking about
[SOC FPGA] custom IP PWM breathing lamp
字符串常量与字符串对象分配内存时的区别
Go language learning notes - Gorm use - native SQL, named parameters, rows, tosql | web framework gin (IX)
[FPGA tutorial case 13] design and implementation of CIC filter based on vivado core
Career experience feedback to novice programmers
Bypass open_ basedir
随机推荐
计算模型 FPS
Three updates to build applications for different types of devices | 2022 i/o key review
Dc-7 target
Rk3399 platform development series explanation (WiFi) 5.52. Introduction to WiFi framework composition
Rk3399 platform development series explanation (WiFi) 5.53, hostapd (WiFi AP mode) configuration file description
JVM command - jmap: export memory image file & memory usage
Redisl garbled code and expiration time configuration
当我们谈论不可变基础设施时,我们在谈论什么
C note 13
c语言(结构体)定义一个User结构体,含以下字段:
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
JVM命令之 jstat:查看JVM統計信息
Audio distortion analysis of DSP and DAC based on adau1452
Database notes 04
一名普通学生的大一总结【不知我等是愚是狂,唯知一路向前奔驰】
Introduction to yarn (one article is enough)
Markdown 并排显示图片
[FPGA] EEPROM based on I2C
Markdown displays pictures side by side
C语言整理(待更新)