第十节 内存映射(Memory Map)
第十节 内存映射(Memory Map)
由 admin 于 周四, 2007-07-26 16:36 提交。mmap is memory map. What it does is to map files into memory. mmap is mainly used as the following purposes.
- read/write files with less overhead
- allocate a bigger memory space (depends on OS)
- shared memory between processes
mmap就是内存映射,为什么需要将文件映射到内存中,mmap主要因为如下目的而被使用:
- 减少读写文件的开销
- 分配一个较大的内存空间(依赖于操作系统)
- 在进程中共享内存
Think about the case that we read all contents from a file. In such a case, we might prepare a buffer and keep reading until the end of the file. It looks as follows:
考虑一下从一个文件中读取全部内容,在这个例子中我们主要准备一个缓冲区并使他保持读入状态直到文件的结束,看起来相如下的代码:
/* naive code to read all contents of a file */
apr_file_t *fp;
apr_file_open(&fp, filename, APR_READ, APR_OS_DEFAULT, mp);
while (1) {
char buf[1024];
apr_size_t len = sizeof(buf);
rv = apr_file_read(fp, buf, &len);
if (rv != APR_SUCCESS) {
break;
}
/* scan buf */
}
apr_file_close(fp);
We can do the same thing with apr_mmap_t as follows:
我们可以是用apr_mmap_t完成同样的工作,如下:
/* excerpted from mmap-sample.c, but I omitted error checks */
apr_file_open(&fp, filename, APR_READ, APR_OS_DEFAULT, mp);
apr_finfo_t finfo;
apr_file_info_get(&finfo, APR_FINFO_SIZE, fp);
apr_mmap_t *mmap;
apr_mmap_create(&mmap, fp, 0, finfo.size, APR_MMAP_READ, mp);
/* scan mmap->mm */
apr_mmap_delete(mmap);
If the file is big enough, mmap based code can be faster.
如果文件越大,则使用mmap方式会比传统的方式效率更高。
More importantly, mmap can be against memory fragmentation. Most of dynamic memory allocation systems have memory fragmentation problem, but mmap is out of such user-space memory allocation managements. Unfortunatelly, on some OSes, mmap might be buggy or slow.
更重要的是mmap可以避免内存的段错误,大多数动态分配内存的系统都会有内存的段错误问题。但是mmap是在用户空间分配管理之外。不幸的是在一些操作系统mmap可能会出现错误或者变得更加缓慢。
We can use mmap to modify files. We open the file with APR_WRITE, and we have to mmap the file with APR_MMAP_WRITE flag.
我们可以使用mmap修改文件,我们使用APR_WRITE打开文件,并且我们需要在mmap文件时使用APR_MMAP_WRITE标志位。
REMARK: You can't mmap the file that is opened with APR_BUFFERED flag. The following code returns APR_EBADF.
备注:你不能映射一个使用APR_BUFFERED标志位打开的文件,如下代码将返回APR_EBADF。
/* BUGGY mmap sample */
apr_file_t *fp;
apr_mmap_t *mm;
apr_file_open(&fp, fname, APR_READ|APR_BUFFERED, APR_OS_DEFAULT, mp);
rv = apr_mmap_create(&mm, fp, 0, finfo.size, APR_MMAP_READ, mp);/* BUG: rv==APR_EBADF */
最新评论
5 天 3 小时 前
6 天 23 小时 前
6 天 23 小时 前
1 周 1 天 前
1 周 1 天 前
4 周 4 天 前
1 年 11 周 前
1 年 11 周 前
1 年 49 周 前
1 年 51 周 前