×
Namespaces

Variants
Actions

QSharedMemory共享内存例子

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata

代码示例
测试基于
设备:: Nokia N96

兼容于
平台: S60 3rd Edition, FP2
Symbian
S60 3rd Edition FP2

文章
关键词: QSharedMemory
翻译:
dougcn
最后由 hamishwillee 在 11 Oct 2012 编辑

Contents

概述

本文借助两个例子SharedMemoryLoad and ShowSharedMem,在Qt上演示称作共享内存(Shared Memory)的进程间(IPC)通讯机制。

说明

Qt使用QSharedMemory类支持共享内存。两个进程可共享相同的内存段进行IPC。

做法

SharedMemoryLoad应用将一个字符串填入共享内存,ShowSharedMem应用显示来自共享内存的字符串

  1. 运行SharedMemoryLoad,然后点击Load按钮;
  2. 在输入对话框中写入一些文本;
  3. 将该应用程序移植后台;
  4. 运行ShowSharedMem应用,然后点击Show from shared memory按钮。在前一个应用输入的文件就显示出来了。

SharedMemoryLoad

SharedMemoryLoad 是一个从QWidget派生的类。它含有QSharedMemory对象作为成员变量:

  class SharedMemoryLoad : public QWidget
{
Q_OBJECT
...
private:
 
QSharedMemory sharedMem;
};

SharedMemoryLoad类的构造函数中,设置共享内存对象的键(key)为"MySharedMemory":

  SharedMemoryLoad::SharedMemoryLoad( QWidget *parent )
: QWidget( parent ),
sharedMem( "MySharedMemory" ) {
...
}

将字符串填入共享内存:

  void SharedMemoryLoad::loadIntoSharedMem()
{
// First, test whether a shared memory segment is already attached to the process.
// If so, detach it
if (sharedMem.isAttached())
{
sharedMem.detach();
}
 
...
 
QBuffer buffer;
buffer.open( QBuffer::ReadWrite );
QDataStream out( &buffer );
out << text;
int size = buffer.size();
 
if ( !sharedMem.create( size ) )
{
ui.LoadButton->setText(tr("Unable to create shared memory segment."));
return;
}
 
// Write into the shared memory
sharedMem.lock();
char *to = (char*)sharedMem.data();
const char *from = buffer.data().data();
memcpy( to, from, qMin( sharedMem.size(), size ) );
sharedMem.unlock();
}


ShowSharedMem

SharedMemoryLoad一样, ShowSharedMem派生自QWidget且拥有一个QSharedMemory对象。

  ShowSharedMem::ShowSharedMem(QWidget *parent)
: QWidget(parent),
sharedMem("MySharedMemory") {
...
}

从共享内存取出:

  void ShowSharedMem::loadFromSharedMem()
{
if (!sharedMem.attach())
{
//If an attempt of reading from the shared memory before data is written
ui.showButton->setText(tr("Enter a text first"));
return;
}
 
QBuffer buffer;
QDataStream in(&buffer);
QString text;
 
sharedMem.lock();
buffer.setData((char*)sharedMem.constData(), sharedMem.size());
buffer.open(QBuffer::ReadOnly);
in >> text;
sharedMem.unlock();
 
// As this is the last process attached to the shared memory segment
// the shared memory segment is released, destroying its contents
sharedMem.detach();
}

样例程序

File:QSharedMemoryExample.zip

注: 本例不能在模拟器上测试,因为在模拟器上运行不了多个Qt应用程序。启动第二个应用时将返回KErrNotSupported(-5).


参阅

Qt Known Issues

This page was last modified on 11 October 2012, at 01:18.
359 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×