/* * problem 9.5, pg 812 : * Use mmap to copy an arbitrary sized file to stdout. * The name of the file should be passed as a command line argument. * * See "man fstat", "man open", "man write". * * $ gcc 9p5.c -o 9p5 * $ ./9p5 9p5.c * ... this file ... * */ #include #include #include #include #include #include /* The mmap call looks like this : void *mmap(void *start, // requested start address size_t length, // int prot, // protections, e.g. PROT_WRITE | PROT_READ int flags, // other options, e.g. MAP_PRIVATE int fd, // file descriptor off_t offset, // ) See man (3) pages for fstat, open, write. See e.g. http://en.wikipedia.org/wiki/Standard_streams for standard streams; (0,2,1) are (stdin, stdout, stderr) */ // Use mmap to copy a file to stdout void mmapcopy(int fd, int size){ char* buffer; // pointer to memory-mapped virtual memory area buffer = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); write(1, buffer, size); return; } int main(int argc, char* argv[]){ int fd; // file descriptor struct stat file_status; // Confirm correct number of arguments. if (argc != 2){ printf("Usage: %s \n", argv[0]); exit(0); } // Open file, get size, do copy. fd = open(argv[1], O_RDONLY, 0); // read-only fstat(fd, &file_status); mmapcopy(fd, file_status.st_size); exit(0); }