apr-tutorial-11.html

来自「跨平台windowsunixlinux的c语言编程解决方案」· HTML 代码 · 共 81 行

HTML
81
字号
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML><HEAD> <META NAME="GENERATOR" CONTENT="LinuxDoc-Tools 0.9.21"> <TITLE>libapr(apache portable runtime) programming tutorial: memory map(mmap)</TITLE> <LINK HREF="apr-tutorial-12.html" REL=next> <LINK HREF="apr-tutorial-10.html" REL=previous> <LINK HREF="apr-tutorial.html#toc11" REL=contents></HEAD><BODY><A HREF="apr-tutorial-12.html">Next</A><A HREF="apr-tutorial-10.html">Previous</A><A HREF="apr-tutorial.html#toc11">Contents</A><HR><H2><A NAME="s11">11.</A> <A HREF="apr-tutorial.html#toc11">memory map(mmap)</A></H2><P>mmap is memory map. What it does is to map files into memory. mmap is mainly used as the following purposes.</P><P>- read/write files with less overhead- allocate a bigger memory space (depends on OS)- shared memory between processes</P><P>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:</P><P><BLOCKQUOTE><CODE><PRE>/* naive code to read all contents of a file */apr_file_t *fp;apr_file_open(&amp;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, &amp;len);   if (rv != APR_SUCCESS) {      break;   }   /* scan buf */}apr_file_close(fp);</PRE></CODE></BLOCKQUOTE></P><P>We can do the same thing with apr_mmap_t as follows:</P><P>/* excerpted from <A HREF="../sample/mmap-sample.c">mmap-sample.c</A>, but I omitted error checks */<BLOCKQUOTE><CODE><PRE>apr_file_open(&amp;fp, filename, APR_READ, APR_OS_DEFAULT, mp);apr_finfo_t finfo;apr_file_info_get(&amp;finfo, APR_FINFO_SIZE, fp);apr_mmap_t *mmap;apr_mmap_create(&amp;mmap, fp, 0, finfo.size, APR_MMAP_READ, mp);/* scan mmap->mm */apr_mmap_delete(mmap);</PRE></CODE></BLOCKQUOTE></P><P>If the file is big enough, mmap based code can be faster.</P><P>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.</P><P>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.</P><P><EM>REMARK</EM>: You can't mmap the file that is opened with APR_BUFFERED flag. The following code returns APR_EBADF.</P><P><BLOCKQUOTE><CODE><PRE>/* BUGGY mmap sample */apr_file_t *fp;apr_mmap_t *mm;apr_file_open(&amp;fp, fname, APR_READ|APR_BUFFERED, APR_OS_DEFAULT, mp);rv = apr_mmap_create(&amp;mm, fp, 0, finfo.size, APR_MMAP_READ, mp);/* BUG: rv==APR_EBADF */</PRE></CODE></BLOCKQUOTE></P><HR><A HREF="apr-tutorial-12.html">Next</A><A HREF="apr-tutorial-10.html">Previous</A><A HREF="apr-tutorial.html#toc11">Contents</A></BODY></HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?