• 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; }
  • 相关阅读:
    HDU5171 GTY's birthday gift —— 矩阵快速幂
    UVA10870 Recurrences —— 矩阵快速幂
    HDU4965 Fast Matrix Calculation —— 矩阵乘法、快速幂
    UVA11551 Experienced Endeavour —— 矩阵快速幂
    D6 I
    亲和串
    Kmp 算法模板 C
    Buy the Ticket
    寒假D3 A Find the Lost Sock
    寒假 D3 D Modular Inverse
  • 原文地址:https://www.cnblogs.com/moodlxs/p/2674748.html
Copyright © 2020-2023  润新知