在函数中使用 mmap()

Using mmap() inside a function

我正在尝试使用 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(true 或 false),因为比较是在赋值之前计算的。尝试

fd = open(inputFile.c_str(), O_RDWR, S_IRUSR);
if(fd == -1 )

改为