mmap 有什么作用?
这行代码是做什么的?
mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
What does this line of code do?
mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
man mmap
将为您提供帮助。它在进程的虚拟地址空间中创建内存映射。它创建一个匿名映射,这很像使用
malloc
来分配n
字节的内存。参数为:
NULL
- 内核将为映射选择一个地址n
- 映射的长度(以字节为单位)PROT_WRITE
- 页可以写成MAP_ANON | MAP_PRIVATE
- 映射不受文件支持,写入映射的更新是进程私有的-1
- 文件描述符;未使用,因为映射不受文件支持0
- 文件内开始映射的偏移量 - 再次未使用,因为映射不受文件支持man mmap
will help you here.It creates a memory mapping in the virtual address space of the process. It's creating an anonymous mapping, which is rather like using
malloc
to allocaten
bytes of memory.The parameters are:
NULL
- the kernel will choose an address for the mappingn
- length of the mapping (in bytes)PROT_WRITE
- pages may be writtenMAP_ANON | MAP_PRIVATE
- mapping is not backed by a file, and updates written to the mapping are private to the process-1
- the file descriptor; not used because the mapping is not backed by a file0
- offset within the file at which to start the mapping - again, not used, because the mapping is not backed by a file它请求 n 字节内存的私有、可写匿名映射。
fork()
之后,子进程和父进程将具有独立的映射);在这种情况下,它本质上是请求一个
n
字节的内存块,因此大致相当于malloc(n)
(尽管必须使用munmap( )
而不是free()
,并且它将是页面对齐的)。它还要求内存可写,但不要求其可读,但是可写和不可读内存通常不是底层硬件支持的组合。当单独请求 PROT_WRITE 时,POSIX 允许实现提供也可以读取和/或可执行的内存。It requests a private, writeable anonymous mapping of
n
bytes of memory.fork()
the child and parent will have independent mappings);In this case, it is essentially requesting a block of
n
bytes of memory, so roughly equivalent tomalloc(n)
(although it must be freed withmunmap()
rather thanfree()
, and it will be page-aligned). It's also requesting that the memory be writeable but not requesting that it be readable, however writeable and unreadable memory is typically not a combination supported by the underlying hardware. WhenPROT_WRITE
alone is requested, POSIX allows the implementation to supply memory that can also be read and/or executable.