Qt进程间通信——共享内存

Qt进程间通信——共享内存_第1张图片

说明

setkey:设置密钥,密钥是Qt应用程序用来标识共享内存段的标识符。
create:创建共享内存空间
lock/unlock:加锁解锁
attach:将进程与共享内存绑定
isAttached:判断是否绑定
detach:解除绑定

代码

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_sharedMemory.setKey("mykey");
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_write_clicked()
{
    if (m_sharedMemory.isAttached())
    {
        if(!m_sharedMemory.detach())
        {
            ui->label_tips->setText("Unable to detach from shared memory.");
            return;
        }
    }

    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << ui->lineEdit_write->text();
    int size = buffer.size();

    if(!m_sharedMemory.create(size))
    {
        ui->label_tips->setText("Unable to create shared memory segment." + m_sharedMemory.errorString());
        return;
    }
    m_sharedMemory.lock();
    char *to = (char*)m_sharedMemory.data();
    const char *from = buffer.data().data();
    memcpy(to,from,qMin(m_sharedMemory.size(),size));
    m_sharedMemory.unlock();
}

void Widget::on_pushButton_read_clicked()
{
    if(!m_sharedMemory.isAttached())
    {
        if(!m_sharedMemory.attach())
        {
            ui->label_tips->setText("Unable to attach to shared memory segment.");
            return;
        }
    }

    QBuffer buffer;
    QDataStream in(&buffer);
    QString str;

    m_sharedMemory.lock();
    buffer.setData((char*)m_sharedMemory.constData(),m_sharedMemory.size());
    buffer.open(QBuffer::ReadOnly);
    in >> str;
    m_sharedMemory.unlock();

    m_sharedMemory.detach();
    ui->lineEdit_read->setText(str);
}

源码下载:https://download.csdn.net/download/sinat_33859977/12367396.

你可能感兴趣的:(QT)