mmap(2)

Paul Falstad pfalstad at phoenix.princeton.edu
Fri May 10 18:25:51 AEST 1991


pefv700 at perv.pe.utexas.edu wrote:
>I'm trying to understand how to use mmap(2) by RTM and am stumped.

>So does anyone have a short and sweet cat(1)-like example that will
>broaden my system call knowledge (at least a little)?

Here's a quick version of cat, without error checking:

-----------------------------------------------------------------------------
#include <stdio.h>
#include <sys/file.h>
#include <sys/mman.h>

main(argc,argv)
int argc;char **argv;
{
char *buf;
int fd,pgsiz,len,off;

   pgsiz = getpagesize()*3;
   fd = open(argv[1],O_RDONLY);
   len = lseek(fd,0,2);
   off = 0;
   buf = NULL;
   for (;;) {
      buf = mmap(buf,pgsiz,PROT_READ,MAP_PRIVATE,fd,off);
      if (len < pgsiz) {
         write(1,buf,len);
         exit(0);
      }
      write(1,buf,pgsiz);
      off += pgsiz;
      len -= pgsiz;
   }
}
-----------------------------------------------------------------------------

This dumps the file in blocks of (pagesize*3).  I picked this value
arbitrarily; the only restriction is that pgsiz must be an integer
multiple of the system page size.

Note that the first time mmap() is called, buf is 0, so the system will
map the file wherever it wants.  After that, the system will map the
file into the same place as before (so we don't accumulate mappings).

--
              Paul Falstad  pfalstad at phoenix.princeton.edu
         And on the roads, too, vicious gangs of KEEP LEFT signs!
     If Princeton knew my opinions, they'd have expelled me long ago.



More information about the Comp.unix.programmer mailing list