* mmap(2)可以替代malloc(3)的功能.
* malloc(3)的实现可能还用到了mmap(2).
mmap(2)是使一个磁盘文件与把存储空间的一个缓冲区相映射,那malloc(3)用mmap(2)实现时, 打开哪个文件?
好奇去下载了glibc src来看了下 [sudo apt-get source glibc-source]
下面的东西解决了我的疑问.
[malloc.c]
[man mmap]
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero. The fd and off-set arguments are ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is only supported on Linux since kernel 2.4.
参考
http://en.wikipedia.org/wiki/Malloc
好奇去下载了glibc src来看了下 [sudo apt-get source glibc-source]
下面的东西解决了我的疑问.
[malloc.c]
/*
Nearly all versions of mmap support MAP_ANONYMOUS,
so the following is unlikely to be needed, but is
supplied just in case.
*/
#ifndef MAP_ANONYMOUS
static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
#define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
(dev_zero_fd = open("/dev/zero", O_RDWR), \
mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
#else
#define MMAP(addr, size, prot, flags) \
(mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
#endif
/*
The main properties of the algorithms are:
* For large (>= 512 bytes) requests, it is a pure best-fit allocator,
with ties normally decided via FIFO (i.e. least recently used).
* For small (<= 64 bytes by default) requests, it is a caching
allocator, that maintains pools of quickly recycled chunks.
* In between, and for combinations of large and small requests,
it does the best it can trying to meet both goals at once.
* For very large requests (>= 128KB by default), it relies on system
memory mapping facilities, if supported.
For a longer but slightly out of date high-level description, see
http://gee.cs.oswego.edu/dl/html/malloc.html
*/
[man mmap]
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero. The fd and off-set arguments are ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is only supported on Linux since kernel 2.4.
参考
http://en.wikipedia.org/wiki/Malloc
没有评论:
发表评论