简体   繁体   English

如何使用mmap在堆中分配内存?

[英]How to use mmap to allocate a memory in heap?

Just the question stated, how can I use mmap() to allocate a memory in heap? 只是问题陈述,如何使用mmap()在堆中分配内存? This is my only option because malloc() is not a reentrant function. 这是我唯一的选择,因为malloc()不是可重入函数。

Why do you need reentrancy? 你为什么需要重入? The only time it's needed is for calling a function from a signal handler; 唯一需要的是从信号处理程序调用函数; otherwise, thread-safety is just as good. 否则,线程安全性也一样好。 Both malloc and mmap are thread-safe. mallocmmap都是线程安全的。 Neither is async-signal-safe per POSIX. 每个POSIX都不是异步信号安全的。 In practice, mmap probably works fine from a signal handler, but the whole idea of allocating memory from a signal handler is a very bad idea. 在实践中, mmap可能在信号处理程序中工作正常,但是从信号处理程序分配内存的整个想法是一个非常糟糕的主意。

If you want to use mmap to allocate anonymous memory, you can use (not 100% portable but definitely best): 如果你想使用mmap来分配匿名内存,你可以使用(不是100%可移植,但绝对是最好的):

p = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

The portable but ugly version is: 便携但丑陋的版本是:

int fd = open("/dev/zero", O_RDWR);
p = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
close(fd);

Note that MAP_FAILED , not NULL , is the code for failure. 请注意, MAP_FAILED而不是NULL是失败的代码。

Make a simple slab allocator 制作一个简单的slab分配器


Although allocating memory in a signal handler 1 does seem like something best avoided, it certainly can be done. 尽管在信号处理程序1中分配内存看起来确实是最好避免的,但它当然可以完成。

No, you can't directly use malloc(). 不,你不能直接使用malloc()。 If you want it to be in the heap then mmap won't work either. 如果你想让它在堆中,那么mmap也不会工作。

My suggestion is that you make a special-purpose slab allocator based on malloc. 我的建议是你制作一个基于malloc的专用slab分配器

Decide exactly what size of object you want and preallocate some number of them. 确切地确定所需对象的大小,并预先分配一些对象。 Allocate them initially with malloc() and save them for concurrent use later. 最初使用malloc()分配它们并保存它们以便以后同时使用。 There are intrinsically reentrant queue-and-un-queue functions that you can use to obtain and release these blocks. 您可以使用本质上可重入的队列和取消队列函数来获取和释放这些块。 If they only need to be managed from the signal handler then even that isn't necessary. 如果只需要从信号处理程序管理它们,那么即使这样也没有必要。

Problem solved! 问题解决了!


1. And if you are not doing that then it seems like you have an embedded system or could just use malloc(). 1.如果你没有这样做,那么你似乎有一个嵌入式系统或者只能使用malloc()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM