13

这行代码有什么作用?

mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
4

2 回答 2

14

它请求n内存字节的私有、可写匿名映射。

  • 私有映射意味着它不与其他进程共享(例如,在fork()子进程和父进程拥有独立映射之后);
  • 匿名映射意味着它不受文件支持。

In this case, it is essentially requesting a block of n bytes of memory, so roughly equivalent to malloc(n) (although it must be freed with munmap() rather than free(), 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. When PROT_WRITE alone is requested, POSIX allows the implementation to supply memory that can also be read and/or executable.

于 2010-09-04T11:31:11.773 回答
11

man mmap会在这里帮助你。

它在进程的虚拟地址空间中创建内存映射。它正在创建一个匿名映射,这很像malloc用于分配n内存字节。

参数是:

  • NULL- 内核将为映射选择一个地址
  • n- 映射的长度(以字节为单位)
  • PROT_WRITE- 页面可以写
  • MAP_ANON | MAP_PRIVATE- 映射不受文件支持,写入映射的更新是进程私有的
  • -1- 文件描述符;未使用,因为映射没有文件支持
  • 0- 文件中开始映射的偏移量 - 再次,未使用,因为映射没有文件支持
于 2010-09-04T11:30:44.100 回答