sharemem.cpp
来自「包含客户和服务器的升级程序,在linux下可以运行的.」· C++ 代码 · 共 179 行
CPP
179 行
/* * Copyright (C) 2006, Binary Ma * Licence: GNU GPL 1991 - version 2 * Bug report: binary@eniak.org*/#include "sharemem.h"#include <sys/mman.h>#include <fcntl.h>#include <unistd.h>#include <sys/vfs.h>#include <sys/mount.h>static const char* VERSION = "0.6.2";memmap::memmap( const char* file, off_t length ){ map = (char*)MAP_FAILED; if( NULL == file ) return; bool create = true; map_size = length; if( map_size < 0 ) { struct stat st; if( -1 == stat( file, &st ) ) return; create = false; map_size = st.st_size; } int fd = open( file, O_RDWR | O_CREAT, 0644 ); if( -1 == fd ) return; if( create ) ftruncate( fd, map_size ); const int MMAP_PROT = PROT_READ | PROT_WRITE; map = (char*)mmap( 0, map_size, MMAP_PROT, MAP_SHARED, fd, 0 ); close( fd );}memmap::~memmap(){ if( MAP_FAILED != map ) { munmap( map, map_size ); map = (char*)MAP_FAILED; }}int memmap::size(){ return map_size;}share::share( int _size, const char* _name ): size( _size ){ eno = 0; buf = (char*)MAP_FAILED; id = -1; create = false; mnt = "/_tmpfs"; name = mnt; if( NULL == _name ) _name = "/shm_default"; else if( *_name != '/' ) name += '/'; name += _name; int flag = O_RDWR | O_SYNC; // for shm_open even then not set flag O_CREAT, // the mode must be explicit set 0 int mode = 0; for( int i = 0; -1 == id && i < 2; i++ ) { if( i != 0 ) { flag |= O_CREAT; mode = 0770; create = true; init_tmpfs(); } id = open( name.c_str(), flag, mode ); } if( -1 == id ) { eno = -__LINE__; return; } if( create ) ftruncate( id, size );}share::share( int _size ): size( _size ){ eno = 0; buf = (char*)MAP_FAILED; id = -1; create = false;}share::~share(){ share_close();}void share::init_tmpfs(){ if( 0 != access( mnt, F_OK ) ) mkdir( mnt, 0777 ); struct statfs vfs; if( 0 == statfs( mnt, &vfs ) ) { // don't include linux/ext2_fs.h, some OS may compile failed, example: debian. // TMPFS_MAGIC == 0x01021994. if( 0x01021994 != vfs.f_type ) mount( NULL, mnt, "tmpfs", 0, NULL ); }}char* share::share_open(){ if( 0 != eno ) return NULL; int flag = MAP_SHARED; if( -1 == id ) flag |= MAP_ANONYMOUS; buf = (char*)mmap( 0, size, PROT_READ | PROT_WRITE, flag, id, 0 ); return buf;}int share::share_close( bool force ){ if( 0 != eno ) return -__LINE__; if( -1 != id ) { close( id ); id = -1; } if( MAP_FAILED != buf ) { munmap( buf, size ); buf = (char*)MAP_FAILED; } int retval = 0; if( create || force ) { retval = remove( name.c_str() ); // if have other process use sharemem, will failed, // so, dont judge return value umount( mnt ); rmdir( mnt ); } return retval;}int share::error(){ return eno;}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?