]> mj.ucw.cz Git - libucw.git/blob - lib/mmap.c
Added bitsig_free().
[libucw.git] / lib / mmap.c
1 /*
2  *      Sherlock Library -- Mapping of Files
3  *
4  *      (c) 1999 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8
9 #include <stdio.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <sys/stat.h>
13 #include <sys/mman.h>
14
15 void *
16 mmap_file(byte *name, unsigned *len, int writeable)
17 {
18   int fd = open(name, writeable ? O_RDWR : O_RDONLY);
19   struct stat st;
20   void *x;
21
22   if (fd < 0)
23     return NULL;
24   if (fstat(fd, &st) < 0)
25     x = NULL;
26   else
27     {
28       if (len)
29         *len = st.st_size;
30       if (st.st_size)
31         {
32           x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
33           if (x == MAP_FAILED)
34             x = NULL;
35         }
36       else      /* For empty file, we can return any non-zero address */
37         return "";
38     }
39   close(fd);
40   return x;
41 }
42
43 void
44 munmap_file(void *start, unsigned len)
45 {
46   munmap(start, len);
47 }