Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!sdd.hp.com!wuarchive!udel!princeton!phoenix!pfalstad From: pfalstad@phoenix.princeton.edu (Paul Falstad) Newsgroups: comp.unix.programmer Subject: Re: mmap(2) Message-ID: <38881@isasun.Princeton.EDU> Date: 10 May 91 08:25:51 GMT References: <48745@ut-emx.uucp> Sender: gnus@idunno.Princeton.EDU Distribution: usa Organization: League For Fighting Chartered Accountancy Lines: 49 pefv700@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 #include #include 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@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.