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

请高手相助: mmap 使用问题,程序执行完后吃掉 100M 内存 !
这是一段测试程序。用   $   top   -p   <pid>   监视内存,发现该进程仅占用   352K   内存,
可是程序执行完后总内存被吃掉   100M   !删除   tmpfile   后,内存恢复到原始状态。

为什么?如何修改?请高手出招,问题解决立刻结贴,谢谢!

//==================================================================

#include   <stdlib.h>
#include   <sys/mman.h>
#include   <sys/types.h>
#include   <fcntl.h>
#include   <unistd.h>
#include   <curses.h>
#include   <string.h>
#include   <iostream>
using   namespace   std;

const   long   FILE_SIZE   =   100   < <   20;
const   long   PAGE_SIZE   =   4   < <   10;
const   long   PAGE_NUM     =   FILE_SIZE   /   PAGE_SIZE;  

int   main()
{
//   reserve
int   fd   =   open(   "tmpfile ",   O_CREAT|O_RDWR|O_TRUNC,   00777   );
if(   fd   <   0   )
{
cout   < <   "Can 't   open   file. "   < <   endl;
                exit(   EXIT_FAILURE   );    
}

if(   lseek(   fd,   PAGE_SIZE*PAGE_NUM-1,   SEEK_SET   )   <   0   )
{
cout   < <   "lseek   error. "   < <   endl;
exit(   EXIT_FAILURE   );
}

char   ch   =   '\0 ';
if(   write(   fd,   &ch,   1   )   !=   1   )
{
cout   < <   "write   error. "   < <   endl;
exit(   EXIT_FAILURE   );
}

cout   < <   "Press   ENTER   to   create   file   ...   ";  
getchar();

void   *pBuf   =   NULL;
for(   int   i   =   0;   i   <   PAGE_NUM;   ++i   )
{
//   mmap
pBuf   =   (int   *)mmap(   NULL,   PAGE_SIZE,   PROT_READ|PROT_WRITE,   MAP_SHARED,   fd,   i*PAGE_SIZE   );

if(   MAP_FAILED   ==   pBuf   )
{
cout   < <   "mmap   error. "   < <   endl;    
exit(   EXIT_FAILURE   );    
}

memset(   pBuf,   0,   PAGE_SIZE   );

if(   munmap(   (caddr_t)pBuf,   PAGE_SIZE   )   <   0   )
{
              cout   < <   "munmap   error "   < <   endl;    
                exit(   EXIT_FAILURE   );    
}
}

close(   fd   );

cout   < <   "Press   ENTER   to   exit   ...   ";  
getchar();

exit(   0   );
}


------解决方案--------------------
const long FILE_SIZE = 100 < < 20;
100M 全是保存在内存中的
------解决方案--------------------
回wgjmail(笑面佛),
和co