简体   繁体   English

使用mmap分配内存

[英]Use mmap to allocate memory

I need to allocate memory but I can't use malloc because its not reentrant, so basically I will implement dynamic memory allocation using POSIX mmap function. 我需要分配内存,但是我不能使用malloc因为它不能重入,所以基本上我将使用POSIX mmap函数实现动态内存分配。 Is it possible to use mmap ? 可以使用mmap吗?

Yes, mmap() should be reentrant so you should be able to use that. 是的,mmap()应该是可重入的,因此您应该可以使用它。 Note that mmap() is often a quite slow operation so you're probably better of using it only in those (hopefully) few and far between cases where it's really needed, rather than as a general purpose malloc() replacement. 请注意,mmap()通常是一个非常慢的操作,因此最好只在确实需要它的情况下(希望)在很少(且很少)之间使用它,而不是用作通用的malloc()替换。

POSIX 2008 contains a list of async-signal-safe functions that are safe to call from a signal handler function (see the table in section 2.4.2 in the link). POSIX 2008包含可以从信号处理程序函数安全调用的异步信号安全函数的列表(请参阅链接中的2.4.2节中的表)。 mmap() is not in that list, that is, calling mmap() from a signal handling function may result in undefined behavior. mmap()不在该列表中,也就是说,从信号处理函数调用mmap()可能导致未定义的行为。

What you can do is to avoid allocating memory in signal handlers, just set some flag and do the actual work later. 您可以做的是避免在信号处理程序中分配内存,只需设置一些标志并在以后进行实际工作即可。

EDIT: replaced reentrant by thread-safe 编辑:用线程安全替换可重入

malloc is thread-safe on most OS. 在大多数操作系统上,malloc是线程安全的。

Which one are you using and are you sure it is not thread-safe? 您正在使用哪一个,并且确定它不是线程安全的? Or do you need it to be reentrant (I guess not)? 还是您需要它可重入(我想不是)?

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

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