日期:2014-05-16  浏览次数:20719 次

mmap 内存映射文件读取的问题
我采用了一个循环读取800多K的文件。
mmap映射的缓存大小是4096字节,
映射后调用write将缓存文件内容写入sockfd缓存。

请问一下,最后一个内存页面不是4K整数倍的时候,
映射的缓存大小还是固定4096吗?
我用write写文件,理论上最后一次循环应该是是写1993字节呀,
怎么最后还是写的4096字节? 求教。。

部门代码如下:

  for(position=1,j=1;j<=((number/2)+1);j++){

  *(int *)str=position;
  *(int *)(str+4)=crccode[position-1];
  Send(str,8);

  mapped=(char *)mmap(0,4096,PROT_READ,MAP_PRIVATE,fd,0);
  if( mapped == MAP_FAILED){
  printf("map failed");
  exit(EXIT_FAILURE);
  }

  len=Write(mapped,4096);
  if( 0 >= len ){
  printf("write error");
  exit(EXIT_FAILURE);
  }
  
  printf("%d : file_block_length:%d\n",position,len);

  munmap(mapped,len);
  position+=2;
  lseek(fd,4096L,SEEK_CUR);
  }

  lseek(fd,4096L,SEEK_SET);

  for(position=2,j=1;j<=((number/2)+1);j++){

  *(int *)str=position;
  *(int *)(str+4)=crccode[position-1];
  Send(str,8);

  mapped=(char *)mmap(0,4096,PROT_READ,MAP_SHARED,fd,0);
  if( mapped == MAP_FAILED){
  printf("map failed");
  exit(EXIT_FAILURE);
  }
  len=Write(mapped,4096);
  if( 0 >= len ){
  printf("write error");
  exit(EXIT_FAILURE);
  }
  printf("%d : file_block_length:%d\n",position,len);

  munmap(mapped,len);

  position+=2;
  lseek(fd,4096L,SEEK_CUR);
  }

大概意思是:先传奇数块文件,再传偶数块文件。

------解决方案--------------------
懒得看代码, 自己读完自己改.


The off argument is constrained to be aligned and sized according to the value returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. When
MAP_FIXED is specified, the application shall ensure that the argument addr also meets these constraints. The implementation performs mapping operations
over whole pages. Thus, while the argument len need not meet a size or alignment constraint, the implementation shall include, in any mapping operation,
any partial page specified by the range [pa,pa+len).

The system shall always zero-fill any partial page at the end of an object. Further, the system shall never write out any modified portions of the last
page of an object which are beyond its end. References within the address range starting at pa and continuing for len bytes to whole pages following
the end of an object shall result in delivery of a SIGBUS signal.