-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmmapi.c
105 lines (96 loc) · 2.52 KB
/
mmapi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*-------------------------------------------------------------------------*/
/**
@file mmapi.c
@author N. Devillard
@brief Interface to map/unmap local files
*/
/*--------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Includes
---------------------------------------------------------------------------*/
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mmapi.h"
/* mmap_open ---------------------------------------------------------------*/
mmap_t * mmap_open(char * filename, size_t max_size, int mode)
{
mmap_t * mm ;
char * buf ;
int fd ;
struct stat fileinfo ;
/* Find out file size in bytes (POSIX compliant) */
if (stat(filename, &fileinfo)!=0) {
perror("stat");
return NULL ;
}
if (max_size==0 && fileinfo.st_size>0) {
/* max_size not requested and file has non-zero size:
* map the whole contents
*/
max_size=fileinfo.st_size;
}
if (fileinfo.st_size>0 && max_size>fileinfo.st_size) {
max_size=fileinfo.st_size;
}
if ((fd = open(filename, O_RDONLY)) == -1) {
perror("open");
return NULL ;
}
buf = (char*)mmap(0,
max_size,
PROT_READ | PROT_WRITE,
mode,
fd,
0) ;
close(fd);
if (buf==(char*)-1) { perror("mmap") ; return NULL ; }
mm = malloc(sizeof(mmap_t)) ;
mm->fd = fd ;
mm->buf = buf ;
mm->size = max_size ;
mm->filename = strdup(filename) ;
return mm ;
}
/* mmap_close() ------------------------------------------------------------*/
void mmap_close(mmap_t * mm)
{
if (mm==NULL) return ;
if (munmap(mm->buf, mm->size)!=0) perror("munmap") ;
if (mm->filename) free(mm->filename) ;
free(mm);
return ;
}
#ifdef MAIN
int main(int argc, char *argv[])
{
char * filename ;
size_t max_size ;
mmap_t * mm ;
if (argc<2) {
printf("use: %s filename [maxsize]\n", argv[0]);
return 1 ;
}
filename = argv[1];
max_size = 0 ;
if (argc>2) {
max_size = (size_t)atoi(argv[2]);
}
mm = mmap_open(filename, max_size, MAP_PRIVATE);
if (!mm) {
printf("cannot map: %s\n", filename);
return -1 ;
}
printf("--contents: %s\n", argv[1]);
printf("%s\n", mm->buf);
printf("--\n");
mmap_close(mm);
return 0 ;
}
#endif
/* vim: set ts=4 et sw=4 tw=75 */