如何使用mmap分配堆内存? [英] How to use mmap to allocate a memory in heap?
问题描述
刚才说的问题,我该如何使用的mmap()
来分配堆内存?这是我唯一的选择,因为的malloc()
不是重入函数。
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.
推荐答案
为什么需要重入?它是唯一需要的时间是调用从信号处理功能;否则,线程安全的一样好。无论的malloc
和 MMAP
是线程安全的。也不是异步信号安全的每POSIX。在实践中, MMAP
可能工作正常从信号处理程序,而是从信号处理程序分配内存的整体思路是一个非常糟糕的主意。
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. Neither is async-signal-safe per 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
来分配匿名内存,你可以使用(不是100%的便携式但绝对最好的):
If you want to use mmap
to allocate anonymous memory, you can use (not 100% portable but definitely best):
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);
注意 MAP_FAILED
,而不是 NULL
,是code失败。
Note that MAP_FAILED
, not NULL
, is the code for failure.
这篇关于如何使用mmap分配堆内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!