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.
相关问题
- Multiple sockets for clients to connect to
- What uses more memory in c++? An 2 ints or 2 funct
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Achieving the equivalent of a variable-length (loc
Make a simple slab allocator
Although allocating memory in a signal handler1 does seem like something best avoided, it certainly can be done.
No, you can't directly use malloc(). If you want it to be in the heap then mmap won't work either.
My suggestion is that you make a special-purpose slab allocator based on 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.
Problem solved!
1. And if you are not doing that then it seems like you have an embedded system or could just use 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
andmmap
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.If you want to use
mmap
to allocate anonymous memory, you can use (not 100% portable but definitely best):The portable but ugly version is:
Note that
MAP_FAILED
, notNULL
, is the code for failure.