以共用記憶體方式讀寫檔案
#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;}