mmap 有什么作用?

发布于 2024-09-17 00:09:12 字数 101 浏览 5 评论 0原文

这行代码是做什么的?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

焚却相思 2024-09-24 00:09:49

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 allocate n bytes of memory.

The parameters are:

  • NULL - the kernel will choose an address for the mapping
  • n - length of the mapping (in bytes)
  • PROT_WRITE - pages may be written
  • MAP_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 file
  • 0 - offset within the file at which to start the mapping - again, not used, because the mapping is not backed by a file
天邊彩虹 2024-09-24 00:09:41

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

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

在这种情况下,它本质上是请求一个 n 字节的内存块,因此大致相当于 malloc(n) (尽管必须使用 munmap( ) 而不是 free(),并且它将是页面对齐的)。它还要求内存可写,但不要求其可读,但是可写和不可读内存通常不是底层硬件支持的组合。当单独请求 PROT_WRITE 时,POSIX 允许实现提供也可以读取和/或可执行的内存。

It requests a private, writeable anonymous mapping of n bytes of memory.

  • A private mapping means it's not shared with other processes (eg, after a fork() the child and parent will have independent mappings);
  • An anonymous mapping means that it's not backed by a file.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文