进程1 初始化
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
if (NULL == m_pSharedMemory)
{
m_pSharedMemory = new QSharedMemory();
QString qstrNativeKey = QString("ShareMemory");
m_pSharedMemory->setNativeKey(qstrNativeKey);
}
// 判断该sm对象是否attch()该内存,是就解除
if (m_pSharedMemory->isAttached())
{
m_pSharedMemory->detach();
}
}
进程1 写数据
void MainWindow::on_pushButton_clicked()
{
QString qstrId = ui->lineEdit->text();
//写入共享内存数据
//gbk编码
QTextCodec* codeSource = QTextCodec::codecForName("GBK");
QByteArray qa = codeSource->fromUnicode(qstrId);
m_pSharedMemory->create(qstrId.toStdString().size());
m_pSharedMemory->lock();
char *to = (char*)m_pSharedMemory->data();
memcpy(to ,qa.data() ,qa.size());
m_pSharedMemory->unlock();
}
进程2 定时器轮询
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this, SLOT(slotScanningSharedMemory()));
this->m_timer->start(1000);
}
进程2 轮询读取共享内存数据
void MainWindow::slotScanningSharedMemory()
{
if (NULL == m_pSharedMemory)
{
m_pSharedMemory = new QSharedMemory();
QString qstrNativeKey = QString("ShareMemory");
m_pSharedMemory->setNativeKey(qstrNativeKey);
}
//先让sm对象attch()到共享内存
if (!m_pSharedMemory->attach(QSharedMemory::ReadOnly))
{
//QMessageBox::information(this, "", "attach failed!");
return;
}
//从共享内存中读取数据
m_pSharedMemory->lock();
QByteArray buffer;
buffer.setRawData((char*)m_pSharedMemory->data(), m_pSharedMemory->size());
//gbk编码
QTextCodec* codeSource = QTextCodec::codecForName("GBK");
QString qstrHouseId = codeSource->toUnicode(buffer.data());
ui->lineEdit->setText("接收结果>>" + qstrHouseId);
m_pSharedMemory->unlock();
//解除attch
m_pSharedMemory->detach();
}