当前位置:网站首页>Deep understanding of MMAP function
Deep understanding of MMAP function
2022-07-22 20:23:00 【Menon poet】
Function introduction
stay Linux Operating system , Process is the basic unit of resource allocation . So each process has its own independent storage space , But in some cases, the processes need to cooperate with each other to complete specific tasks , This makes interprocess communication very necessary . There are many ways to communicate between processes , Of course, this is not the focus of our discussion in this section , This section mainly talks about mmap function , It's through Map a piece of physical memory to the virtual address space of multiple processes , To complete the reading and writing of the same physical memory by multiple processes Thus, the communication between processes can be realized .
Have a look first mmap Function prototype of function , as follows :
Parameter description :
addr: The starting address of the mapping area , Set to NULL Indicates that the starting address of the mapping area is determined by the system .
length: The length of the mapping area .// The unit of length is In bytes , Less than one memory page is processed as one memory page
prot: Expected memory protection flag , Cannot conflict with file open mode . Is one of the following values , Can pass or The operations are reasonably combined
PROT_READ // Page content can be read
PROT_WRITE // Pages can be written to
flags: Specifies the type of mapping object , Whether mapping options and mapping pages can be shared . Its value can be one or more combinations below
MAP_SHARED // Share the mapping space with all other processes that map this object . Write to share , Equivalent to output to a file . until msync() perhaps munmap() Called , The file is not actually updated .
MAP_PRIVATE // Create a private map to copy on write . The writing of memory area will not affect the original file . This flag and the above flags are mutually exclusive , Use only one of .
MAP_ANONYMOUS // Anonymous mapping , The map area is not associated with any files , Shorthand for :MAP_ANON.
fd: Valid file descriptors .
offset: The offset of the mapped object content (4K Integer multiple ).Return value description :
On successful execution ,mmap() Returns a pointer to the mapped area , return MAP_FAILED( Its value is (void *)-1).
Procedure cases
Case a : Process passing fork When a function generates a child process , We know Except that the open file descriptor of the parent process is shared by the child process , Also, the parent process calls mmap The mapping address space generated by the function is shared by parent-child processes . Look at a case as follows :
/************************************** do person : lijd Generated on : 2021 year 02 month 06 Japan Function description : mmap Function case test **************************************/ #include <sys/mman.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc,char **argv) { int ret, inum = 0; #if 0 // This segment is replaced by anonymous mapping area int fd = open("mytest.txt", O_CREAT|O_RDWR, 0644); if(fd < 0) { perror("open feild!"); return -1; } ret = ftruncate(fd, 4); if(ret == -1) { perror("ftruncate feild!"); return -1; } char *ptr = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(ptr == MAP_FAILED) { perror("mmap feild!"); return -1; } close(fd); #else char *ptr = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); if(ptr == MAP_FAILED) { perror("mmap feild!"); return -1; } #endif *(int *)ptr = 1234; printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); pid_t pid = fork(); if(pid == 0) // son { *(int *)ptr = 5678; inum = 6666; printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); } if(pid > 0) // father { wait(NULL); printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); ret = munmap(ptr, 4); if(ret == -1) { perror("munmap feild!"); return -1; } } return 0; }
The results are as follows :
Analyze the execution results of the above figure : At first ptr The memory space pointed to is called to mmap After the function is applied to the space , The parent process makes its stored value :1234, Variables inum The value of is 0, When fork After creating a subprocess , In the sub process, the pointer is always ptr The executed content value is modified to :5678, Variable inum The value of a 6666. When the child process finishes executing, the pointer in the parent process ptr The content in becomes the modified value of the child process , Variables inum Or before 0. Because parent-child processes share mmap Function to create memory , When the child process is modified inum Variable time subprocess uses write time copy technology , by inum The variable reapplied for memory to store the modified new value .
The above case is the communication between father and son processes , If the communication between processes is not related by blood, you only need to call mmap Map the same file , No more details here .
Case 2 : Let's think about it , If two processes can communicate by opening the same file ? Look at the following case :
process 1 Code :
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc,char **argv) { int ret = 0; char buf[256] = {0}; char *str = "-----------------lijd 1111---------------------\n"; int fd = open("mytest.txt", O_CREAT|O_RDWR|O_TRUNC, 0644); write(fd, str, strlen(str)); printf("test1 write mytest.txt finish!\n"); lseek(fd, 0, SEEK_SET); sleep(10); ret = read(fd, buf, sizeof(buf)); printf("mytest.txt : %s\n", buf); close(fd); return 0; }
process 2 Code :
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc,char **argv) { int ret = 0; char buf[256] = {0}; char *str = "-----------------lijd 2222---------------------\n"; int fd = open("mytest.txt", O_RDWR); ret = read(fd, buf, sizeof(buf)); printf("mytest.txt : %s\n", buf); write(fd, str, strlen(str)); printf("test2 write mytest.txt finish!\n"); close(fd); return 0; }
The two processes execute the process first 1, And then in 10 Execute process in seconds 2; The results are as follows :
Analysis of the above structure shows that two processes can realize inter process communication by opening the same file . We further use strace The system call of the command tracking process is shown in the figure below :
use strace Command trace knows the process 1 The underlying system call is also through the call mmap Function to realize memory mapping for data sharing between processes , Therefore, we have a deeper understanding mmap The use of functions .
边栏推荐
猜你喜欢
Elastic Search 学习入门之核心概念(四)
她力量系列六丨杨笛一:女孩长大后数理化可以很好,科研可以很鲜活
图的深度优先搜索和广度优先搜索
Core concepts of elastic search learning Introduction (4)
她力量系列二丨UCLA李婧翌:女性最不需要做的就是「怀疑自己」
How to deal with DNS hijacking, DNS hijacking, and DNS hijacking solutions
RetinaNet:Focal Loss for Dense Object Detection
蓝桥杯省赛训练营——常用STL
Elastic Search 学习入门之Elastic Search的安装配置(一)
信号降噪方法
随机推荐
蓝桥杯——进制转换练习
网站安全之域名被劫持、域名被劫持后该怎么办!!!
Nc54 sum of three numbers
What should I do if the web page is hijacked? How to repair DNS hijacked? Introduction to web hijacking
linux Redis下载及安装
How to solve the blue screen problem in win8.1 system and how to solve the malicious hijacking of IE home page?
使用CSDN-markdown编辑器入门
Leetcode 32. longest valid bracket
域名劫持定义及原理、域名被劫持解决办法有那些
Dense Passage Retrieval for Open-Domain Question Answering笔记
Introduction to machine learning: Logistic regression-2
yum安装提示保护多库版本
Iptables for load balancing
LeetCode53——Maximum Subarray——3 different methods
Introduction to elastic search: Restful advanced query operations (IX)
What are the definitions and principles of domain name hijacking and the solutions to domain name hijacking
MySql分页
What does Baidu snapshot hijacking mean? How to solve Baidu snapshot hijacking and Baidu hijacking
Leetcode 22. bracket generation
图的深度优先搜索和广度优先搜索