系统调用——文件与内存映射

一 文件与内存映射

1 代码

#include <sys/mman.h> /* for mmap and munmap */  
#include <sys/types.h> /* for open */  
#include <sys/stat.h> /* for open */  
#include <fcntl.h>     /* for open */  
#include <unistd.h>    /* for lseek and write */  
#include <stdio.h>  
  
int main(int argc, char **argv)  
{  
    int fd;  
    char *mapped_mem, * p;  
    int flength = 1024;  
    void * start_addr = 0;  
  
    fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);  
    flength = lseek(fd, 1, SEEK_END);  
    write(fd, "\0", 1); /* 在文件最后添加一个空字符,以便下面printf正常工作 */  
    lseek(fd, 0, SEEK_SET);  
    mapped_mem =(char*) mmap(start_addr,
        flength,
        PROT_READ,        //允许读  
        MAP_PRIVATE,       //不允许其它进程访问此内存区域  
        fd,
        0);  
      
/* 使用映射区域. */  
    printf("%s\n", mapped_mem); /* 为了保证这里工作正常,参数传递的文件名最好是一个文本文件 */  
    close(fd);  
    munmap(mapped_mem, flength);  
    return 0;  
}  

2 运行

[root@localhost test]# touch myfile.txt
[root@localhost test]# echo "hello boy">>myfile.txt
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test myfile.txt
hello boy

二 修改文件内存映射

1 代码

#include <sys/mman.h> /* for mmap and munmap */  
#include <sys/types.h> /* for open */  
#include <sys/stat.h> /* for open */  
#include <fcntl.h>     /* for open */  
#include <unistd.h>    /* for lseek and write */  
#include <stdio.h>  
#include <string.h> /* for memcpy */  
      
int main(int argc, char **argv)  
{  
    int fd;  
    char *mapped_mem, * p;  
    int flength = 1024;  
    void * start_addr = 0;  
      
    fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);  
    flength = lseek(fd, 1, SEEK_END);  
    write(fd, "\0", 1); //在文件最后添加一个空字符,以便下面printf正常工作
    lseek(fd, 0, SEEK_SET);  
    start_addr = (void*)0x80000;  
    mapped_mem = (char*)mmap(start_addr,
        flength,
        PROT_READ|PROT_WRITE,        //允许写入  
        MAP_SHARED,       //允许其它进程访问此内存区域  
        fd,
        0);  
      
    // 使用映射区域.
    printf("%s\n", mapped_mem); //为了保证这里工作正常,参数传递的文件名最好是一个文本文  
    while ((p = strstr(mapped_mem, "hello"))) { // 此处来修改文件 内容
        memcpy(p, "Linux", 5);  
        p += 5;  
    }  
          
    close(fd);  
    munmap(mapped_mem, flength);  
    return 0;  
}  

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test myfile.txt
hello boy

[root@localhost test]# cat myfile.txt
Linux boy

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值