在函数中使用 mmap()



我正在尝试使用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 bytesn", sb.st_size);
int B = 5000;
int pages = int(ceil((double)B/PAGESIZE));
printf("mmap will map %d pages for a total of %d bytesn", pages, pages*PAGESIZE);
char * map = (char*)mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd,0);
printf("map:t%pn", map);
printf("%cn", 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 filen");
exit(1);
}
struct stat sb;
if(fstat(fd,&sb)==-1) {
perror("could not get file size");
exit(1);
}
printf("File size is %ld bytesn", 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 bytesn", pages, pages*pagesize);
char* map = (char*) mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd, 0);
printf("map:t%pn", map);
printf("%cn", map[0]);
}

mmap(( 不起作用,我得到一个 seg 错误:

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 )

相反

相关内容

  • 没有找到相关文章

最新更新