/* * mmap-test.c */ #include #include #include #include #include #include #include int main(int argc, char *argv[]) { char *file_data; struct stat sb; int fd; char buf[1]; /* open the file */ if((fd = open("test-file", O_RDONLY)) < 0) { perror("open"); exit(1); } /* get file metadata including, most especially, its size */ if(fstat(fd, &sb) < 0) { perror("fstat"); exit(2); } /* pause */ write(1, "hit enter to mmap\n", 18); read(0, buf, 1); /* set up the mapping */ file_data = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if(file_data == MAP_FAILED) { perror("mmap"); exit(3); } printf("file is mapped at address %p\n", file_data); /* write the data to stdout */ if(write(1, file_data, sb.st_size) < 0) { perror("write"); exit(4); } /* write the data to stdout, this time with more pointer arithmetic */ if(write(1, file_data + 13, sb.st_size - 13) < 0) { perror("write"); exit(5); } /* pause */ write(1, "hit enter to munmap\n", 20); read(0, buf, 1); /* clean up after ourselves */ if(munmap(file_data, sb.st_size) < 0) { perror("munmap"); exit(6); } if(close(fd) < 0) { perror("close"); exit(7); } }