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; }

原文链接: https://www.cnblogs.com/moodlxs/archive/2012/09/07/2674748.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Linux Posix 共享内存操作

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/390615

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月30日 下午3:52
下一篇 2023年3月30日 下午3:52

相关推荐