QSharedMemory

QSharedMemory

1.setKey(),这是标记共享内存的一个标识符,

在整个操作系统的共享内存中,用这个key去标识它,唯一标识。



2.首先是create(),创建共享内存,向os申请内存空间

如果不创建,调用attach()会失败,

在create()的时候,需要制定共享内存的大小,即字节数,

跟windows的CreateFileMapping()一样,都是需要在create()的时候指定,而且大小是固定的,




3.

从共享内存读取数据的时候,必须要先绑定,写入数据不需要attach()


attach()函数,在workstation.exe进程中,调用 该共享内存的attach()函数,

注意是,将该exe绑定到该共享内存中,

如果要读取某个共享内存,必须要想将exe绑定到共享内存中,只有绑定成功,才能读取,

 Returns true if the attach operation is successful. If false is returned,



bool QSharedMemory::detach ()

一定要注意这个函数,系统会自动释放该共享内存,导致其data()返回为空,

Detaches the process from the shared memory segment. If this was the last process attached to the shared memory segment, then the shared memory segment is released by the system, i.e., the contents are destroyed.

The function returns true if it detaches the shared memory segment. If it returns false, it usually means the segment either isn't attached, or it is locked by another process.


void test_sharedMemory::WriteMem()
{
    bool b ;

m_mem.create( 1024 );//创建共享内存,

    if ( m_mem.isAttached() )
    {
        b = m_mem.detach();//释放共享内存了,因为这个共享内存只有当前进程使用它,

    }

    char * pMem = static_cast<char*>( m_mem.data() );//data()返回为空
    if ( pMem == NULL )
    {
        qDebug()<<"获取memory失败";
    }



detach()后,虽然该块共享内存的地址为null,但是它的key还是存在的,因此,可以继续调用create(),重新申请内存,然后就可以继续使用了,






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值