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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4779188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:36:02  来源:igfitidea点击:

How to use mmap to allocate a memory in heap?

cmemory-managementheapmmap

提问by domlao

Just the question stated, how can I use mmap()to allocate a memory in heap? This is my only option because malloc()is not a reentrant function.

刚刚提到的问题,我如何使用mmap()在堆中分配内存?这是我唯一的选择,因为malloc()它不是可重入函数。

回答by R.. GitHub STOP HELPING ICE

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 mallocand mmapare thread-safe. Neither is async-signal-safe per POSIX. In practice, mmapprobably works fine from a signal handler, but the whole idea of allocating memory from a signal handler is a very bad idea.

为什么需要重入?唯一需要的时间是从信号处理程序调用函数;否则,线程安全也一样好。这两个mallocmmap是线程安全的。每个 POSIX 都不是异步信号安全的。在实践中,mmap可能在信号处理程序中工作得很好,但是从信号处理程序分配内存的整个想法是一个非常糟糕的主意。

If you want to use mmapto 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是失败的代码。

回答by DigitalRoss

Make a simple slab allocator

制作一个简单的slab分配器



Although allocating memory in a signal handler1does seem like something best avoided, it certainly can be done.

尽管在信号处理程序1中分配内存似乎是最好避免的事情,但它确实可以做到。

No, you can't directly use malloc(). If you want it to be in the heap then mmap won't work either.

不,您不能直接使用 malloc()。如果您希望它在堆中,那么 mmap 也不起作用。

My suggestion is that you make a special-purpose slab allocatorbased on malloc.

我的建议是,您可以基于 malloc制作一个专用的平板分配器

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. 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.

准确确定您想要的对象大小并预先分配一些对象。最初使用 malloc() 分配它们并保存它们以供以后并发使用。您可以使用本质上可重入的队列和取消队列函数来获取和释放这些块。如果它们只需要从信号处理程序进行管理,那么即使这样也没有必要。

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()。