我正在尝试使用mmap使用对象函数将文件放入内存。我认为我的指针有问题,但我无法真正解决。当我在main()中使用mmap时,一切顺利:
int main(){
int fd = open("../../../some_file.txt", O_RDONLY, S_IRUSR);
struct stat sb;
if(fstat(fd,&sb)==-1) {
perror("could not get file size");
exit(1);
}
printf("File size is %ld bytes\n", sb.st_size);
int B = 5000;
int pages = int(ceil((double)B/PAGESIZE));
printf("mmap will map %d pages for a total of %d bytes\n", pages, pages*PAGESIZE);
char * map = (char*)mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd,0);
printf("map:\t%p\n", map);
printf("%c\n", map[0]);
int res = munmap(map, B);
}
并且我得到以下(预期的)输出:
File size is 73004383 bytes
mmap will map 2 pages for a total of 8192 bytes
map: 0x7fb8b0bed000
J
每当我尝试从对象函数中使用mmap时,都会出现问题:
int main(){
string inputFile = "../../../some_file.txt";
Input* input = new Input();
input->read_test(inputFile);
}
class Input{
Input(void){ }
void read_test(const string &inputFile) {
if(fd = open(inputFile.c_str(), O_RDWR, S_IRUSR) == -1 ){
perror("Error while opening the file\n");
exit(1);
}
struct stat sb;
if(fstat(fd,&sb)==-1) {
perror("could not get file size");
exit(1);
}
printf("File size is %ld bytes\n", sb.st_size);
int B = 5;
int pages = int(ceil((double)B/pagesize));
printf("mmap will map %d page(s) for a total of %d bytes\n", pages, pages*pagesize);
char* map = (char*) mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd, 0);
printf("map:\t%p\n", map);
printf("%c\n", map[0]);
}
mmap()无法正常工作,并且出现段错误:
File size is 73004383 bytes
mmap will map 1 page(s) for a total of 4096 bytes
map: 0xffffffffffffffff
./main line 3: 6505 Segmentation fault (core dumped) ./main
在此行
if(fd = open(inputFile.c_str(), O_RDWR, S_IRUSR) == -1 )
fd设置为0或1(是或否),因为比较是在赋值之前求值的。尝试
fd = open(inputFile.c_str(), O_RDWR, S_IRUSR);
if(fd == -1 )
代替