
mmap示例
As programmers we generally use malloc()
, free()
and similar functions in order to allocate memory. They are provided by glibc()
library. The actual work is done by mmap()
and munmap()
which is a Linux systemcall.
作为程序员,我们通常使用malloc()
, free()
和类似函数来分配内存。 它们由glibc()
库提供。 实际工作由mmap()
和munmap()
,这是Linux系统调用。
mmap()有什么功能? (What Does mmap() Function?)
mmap()
function or system call will create a mapping in the virtual meory of the current process.The address space consist of multiple pages and each page can be mapped some resource. We can create this mapping for a resources we want to use.
mmap()
函数或系统调用将在当前进程的虚拟内存中创建一个映射。地址空间由多个页面组成,每个页面都可以映射一些资源。 我们可以为要使用的资源创建此映射。
图书馆 (Library)
mmap()
and munmap()
functions are provided by sys/mman.h
library. so in order to use we need to include them like below.
mmap()
和munmap()
函数由sys/mman.h
库提供。 因此,要使用它,我们需要像下面这样包含它们。
#include <sys/mman.h>
句法 (Syntax)
As mmap()
provides flexible memory mapping it has a lot of parameters to use.
由于mmap()
提供了灵活的内存映射,因此它具有许多要使用的参数。
void *mmap(void *addr, size_t lengthint " prot ", int " flags ,
int fd, off_t offset)
void *addr
is the address we want to start mappingvoid *addr
是我们要开始映射的地址size_t lengthint
is the size we want to map in as integersize_t lengthint
是我们要映射为整数的大小PROT_READ|PROT_WRITE|PROT_EXEC
options about page关于页面的
PROT_READ|PROT_WRITE|PROT_EXEC
选项MAP_ANON|MAP_PRIVATE
options about page关于页面的
MAP_ANON|MAP_PRIVATE
选项
内存映射类型(Memory Mapping Types)
We have two option about memory mapping for sharing.
关于共享的内存映射,我们有两个选择。
MAP_SHARED
will map given page and this will be also visible by other processes.MAP_SHARED
将映射给定的页面,其他进程也将看到它。MAP_PRIVATE
will map given page and this will not visible to other processes.MAP_PRIVATE
将映射给定的页面,而这对于其他进程将不可见。
例 (Example)
Here is an example which takes a page from start of 2^20
. The default size of the page is 4096
byte so we will map a page with 4096 byte memory.
这是一个从2^20
开始的页面示例。 页面的默认大小是4096
字节,因此我们将映射一个具有4096字节内存的页面。
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void) {
size_t pagesize = getpagesize();
printf("System page size: %zu bytes\n", pagesize);
char * region = mmap(
(void*) (pagesize * (1 << 20)), // Map from the start of the 2^20th page
pagesize, // for one page length
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_ANON|MAP_PRIVATE, // to a private block of hardware memory
0,
0
);
if (region == MAP_FAILED) {
perror("Could not mmap");
return 1;
}
strcpy(region, "Hello, poftut.com");
printf("Contents of region: %s\n", region);
int unmap_result = munmap(region, 1 << 10);
if (unmap_result != 0) {
perror("Could not munmap");
return 1;
}
// getpagesize
return 0;
}
When we compile with the following command the a.out
executable will be generated.
当我们使用以下命令编译时,将生成a.out
可执行文件。
$ gcc main.c

翻译自: https://www.poftut.com/mmap-tutorial-with-examples-in-c-and-cpp-programming-languages/
mmap示例