#include #include #include #include #include #include #include /* * An implementation of copy ("cp") that uses memory maps. Various * error checking has been removed to promote readability */ // Where we want the source file's memory map to live in virtual memory // The destination file resides immediately after the source file #define MAP_LOCATION 0x6100 int main (int argc, char *argv[]) { int fdin, fdout; char *src, *dst; struct stat statbuf; off_t fileSize = 0; if (argc != 3) { printf ("usage: a.out \n"); exit(0); } /* open the input file */ if ((fdin = open (argv[1], O_RDONLY)) < 0) { printf ("can't open %s for reading\n", argv[1]); exit(0); } /* open/create the output file */ if ((fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC, 0600)) < 0) { printf ("can't create %s for writing\n", argv[2]); exit(0); } /* find size of input file */ fstat (fdin,&statbuf) ; fileSize = statbuf.st_size; /* go to the location corresponding to the last byte */ if (lseek (fdout, fileSize - 1, SEEK_SET) == -1) { printf ("lseek error\n"); exit(0); } /* write a dummy byte at the last location */ write (fdout, "", 1); /* * memory map the input file. Only the first two arguments are * interesting: 1) the location and 2) the size of the memory map * in virtual memory space. Note that the location is only a "hint"; * the OS can choose to return a different virtual memory address. * This is illustrated by the printf command below. */ src = mmap ((void*) MAP_LOCATION, fileSize, PROT_READ, MAP_SHARED, fdin, 0); /* memory map the output file after the input file */ dst = mmap ((void*) MAP_LOCATION + fileSize , fileSize , PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0); printf("Mapped src: 0x%x and dst: 0x%x\n",src,dst); /* Copy the input file to the output file */ memcpy (dst, src, fileSize); // we should probably unmap memory and close the files } /* main */