Linux Posix 共用記憶體操作

來源:互聯網
上載者:User
以共用記憶體方式讀寫檔案
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <fcntl.h>#include <sys/mman.h>#include <sys/types.h>#include <sys/stat.h>#include <stdint.h>#include "timediff.h"int main( int argc, char ** argv ){    const uint32_t SHM_SIZE  = 200*1024*1024;    int         fd;    char* ptr = NULL;    if( argc != 2 )    {        printf("Enter your file name!\n");        exit( EXIT_FAILURE );    }    if( ( fd = open( argv[1], O_RDWR|O_CREAT, 0666 ) ) < 0 )    {        perror( argv[1] );        exit(EXIT_FAILURE);    }    /// 修改檔案長度為共用記憶體長度    ftruncate(fd, SHM_SIZE);    /// 以寫方式映射    if( ( ptr = (char*)mmap( 0, SHM_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 ) ) == MAP_FAILED )    {        perror("mmap");        exit( EXIT_FAILURE );    }    memset(ptr,'a', SHM_SIZE/4);    /// 加個時間點檢查,比較MS_ASYNC和MS_SYNC的時間差異    //Timediff td;    //td.start();
// msync非同步模式也很有意思,測試發現,執行該函數後,即使馬上讓程式coredown, 資料也可以成功寫出而不會丟失
  // 寫200M的資料,非同步模式只用了4us, 如果採用同步模式,則時間是原來的千倍萬倍! msync(ptr, SHM_SIZE/4, MS_ASYNC); //msync(ptr, SHM_SIZE/4, MS_SYNC); //td.end(); //std::cout << "sync td:" << td.getUsTimeDiff() << std::endl; munmap(ptr, SHM_SIZE); ///修本文件大小,改為實際內容的長度 ftruncate(fd, SHM_SIZE/4); close(fd); return 0;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.