packio-simple

annotate src/memmap.c @ 2:4767e7769c32

packio-simple has more chances to ever get done
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 09 Aug 2015 05:14:29 +0300
parents
children
rev   line source
nuclear@2 1 #include <stdio.h>
nuclear@2 2 #include <string.h>
nuclear@2 3 #include <errno.h>
nuclear@2 4 #include "memmap.h"
nuclear@2 5
nuclear@2 6 #if defined(__unix__) || defined(__APPLE__)
nuclear@2 7 #include <unistd.h>
nuclear@2 8 #include <fcntl.h>
nuclear@2 9 #include <sys/mman.h>
nuclear@2 10 #include <sys/stat.h>
nuclear@2 11
nuclear@2 12 int map_file(struct mmfile *mm, const char *fname)
nuclear@2 13 {
nuclear@2 14 int fd;
nuclear@2 15 struct stat st;
nuclear@2 16
nuclear@2 17 if((fd = open(fname, O_RDONLY)) == -1) {
nuclear@2 18 fprintf(stderr, "map_file: failed to open %s: %s\n", fname, strerror(errno));
nuclear@2 19 return -1;
nuclear@2 20 }
nuclear@2 21 fstat(fd, &st);
nuclear@2 22
nuclear@2 23 if((mm->ptr = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == (void*)-1) {
nuclear@2 24 close(fd);
nuclear@2 25 fprintf(stderr, "map_file: failed to map file %s: %s\n", fname, strerror(errno));
nuclear@2 26 return -1;
nuclear@2 27 }
nuclear@2 28 mm->size = st.st_size;
nuclear@2 29
nuclear@2 30 close(fd);
nuclear@2 31 return 0;
nuclear@2 32 }
nuclear@2 33
nuclear@2 34 void unmap_file(struct mmfile *mm)
nuclear@2 35 {
nuclear@2 36 munmap(mm->ptr, mm->size);
nuclear@2 37 }
nuclear@2 38
nuclear@2 39 #else
nuclear@2 40 /* implement on win32 */
nuclear@2 41 #endif