zoukankan      html  css  js  c++  java
  • Linux Posix 共享内存操作

    以共享内存方式读写文件

    #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; }
  • 相关阅读:
    写在之前
    Fedora Core 3安装杂记(三)
    Fedora Core 3安装杂记(一)
    Firefox 1.0真的挺好用的
    发现Google加了英文页面翻译功能(Beta)
    Fedora Core 3安装杂记(四)
    在FC3的日子里……
    ASP面向对象编程探讨及比较
    显卡千万不能买带风扇的……
    字符串(strcat)
  • 原文地址:https://www.cnblogs.com/moodlxs/p/2674748.html
Copyright © 2011-2022 走看看