linux C學習筆記04--記憶體映射

來源:互聯網
上載者:User

標籤:

記憶體映射代碼,開啟一個檔案與映射到記憶體中,對記憶體和檔案的修改都會反映到檔案中來,反之亦然,先貼代碼,以後再完善:

 

/*************************************************************************    > File Name: memory_map.c    > Author: hailin.ma    > Mail: [email protected]     > Created Time: Thu 28 May 2015 08:20:50 AM CST ************************************************************************/#include<stdio.h>#include <sys/mman.h>#include <fcntl.h>#include <string.h>#define MEM_MAP_SIZE 1000int memory_map(){    char * pmap = NULL;    int fd;    char rdbuf[100] = "\0";    fd = open("memory.txt",O_RDWR|O_CREAT|O_TRUNC,0660);    if(fd == -1)    {        perror("open error");        return -1;    }    write(fd,"hello world!",MEM_MAP_SIZE);        //write data to file,the write size must as long as MEM_MAP_SIZE        pmap = mmap(NULL,MEM_MAP_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);        //map memory with file    printf("the memory is: %s\n",pmap);    memset(pmap,‘a‘,MEM_MAP_SIZE);    memcpy(pmap,"this is memory map",18);        //try to chang any charactor in memory        lseek(fd,0,SEEK_SET);            //move fd pointer to begin section        memset(rdbuf,0,sizeof(rdbuf));    read(fd,rdbuf,100);                //read the context in file    printf("the file is: %s\n",rdbuf);    munmap(pmap,10);    close(fd);    return 0;}


 

main函數調用後運行:

linux C學習筆記04--記憶體映射

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.