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(),重新申请内存,然后就可以继续使用了,