2 // Copyright (c) 2010-2017 Intel Corporation
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
27 #include "mappedfile.hpp"
29 static void zeroOutFile(int fd, size_t size)
31 void *empty = calloc(1, 4096);
34 write(fd, empty, 4096);
37 write(fd, empty, size);
41 int MappedFile::open(const string& filePath, size_t size)
43 mappedFileSize = size;
45 fd = ::open(filePath.c_str(), O_RDWR | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
47 cerr << "Failed to open file " << filePath << ":" << strerror(errno) << endl;
51 zeroOutFile(fd, size);
52 data = mmap(NULL, mappedFileSize, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0);
54 if (data == MAP_FAILED) {
55 cerr << "Failed to map file: " << strerror(errno) << endl;
61 static size_t getFileSize(const string& filePath)
64 if (stat(filePath.c_str(), &s))
70 int MappedFile::open(const string& filePath)
72 mappedFileSize = getFileSize(filePath);
74 fd = ::open(filePath.c_str(), O_RDONLY);
76 cerr << "Failed to open file " << filePath << ":" << strerror(errno) << endl;
80 data = mmap(NULL, mappedFileSize, PROT_READ, MAP_SHARED, fd, 0);
82 if (data == MAP_FAILED) {
83 cerr << "Failed to map file: " << strerror(errno) << endl;
89 int MappedFile::sync()
91 if (msync(data, mappedFileSize, MS_SYNC) == -1) {
92 cerr << "Failed to sync: " << strerror(errno) << endl;
99 void MappedFile::close()
102 munmap(data, mappedFileSize);
106 size_t MappedFile::size() const
108 return mappedFileSize;