]> mj.ucw.cz Git - moe.git/blob - ucw/mmap.c
Merge branch 'layout'
[moe.git] / ucw / mmap.c
1 /*
2  *      UCW Library -- Mapping of Files
3  *
4  *      (c) 1999--2002 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11
12 #include <stdio.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <sys/stat.h>
16 #include <sys/mman.h>
17
18 void *
19 mmap_file(const char *name, unsigned *len, int writeable)
20 {
21   int fd = open(name, writeable ? O_RDWR : O_RDONLY);
22   struct stat st;
23   void *x;
24
25   if (fd < 0)
26     die("open(%s): %m", name);
27   if (fstat(fd, &st) < 0)
28     die("fstat(%s): %m", name);
29   if (len)
30     *len = st.st_size;
31   if (st.st_size)
32     {
33       x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
34       if (x == MAP_FAILED)
35         die("mmap(%s): %m", name);
36     }
37   else  /* For empty file, we can return any non-zero address */
38     x = "";
39   close(fd);
40   return x;
41 }
42
43 void
44 munmap_file(void *start, unsigned len)
45 {
46   munmap(start, len);
47 }