mmap函数 简单应用 晓萍请看

2015阅读 1评论2011-10-30 随1意2o
分类:C/C++

panda@panda-G31M-ES2C:~/code/c$ cat m_map.c
#include
#include
#include  /*提供类型pid_t,size_t的定义*/
#include
#include
#include
int main(void)
{
    int fd;
    char *buf = NULL;
    int i;
    //打开一个文件
    if (-1 == (fd = open("mapping_file.txt",O_RDWR,0)))
    {
            printf("open file error!\n");
               exit(1);
    }
    
    //将文件映射到进程的一个内存区域
    buf = mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (!buf)
    {
        printf("mmap error!\n");
        exit(1);
    }
    
    //对映射内存读数据
    for (i = 0; i < 100; i++)
        printf("%c", buf[i]);
        
    //对映射内存写数据
    if (buf[0] == 'H')
        buf[0] = 'h';
    else
        buf[0] = 'H';
    system("cat mapping_file.txt");
       return 0;
    
}
panda@panda-G31M-ES2C:~/code/c$ ./m_map
Hello world
hello world
 
代码运行无误,仔细看看就会理解了
上一篇:从10000个数中找出前5大的数
下一篇:“/bin/bash^M: bad interpreter: No such file or directory  

文章评论