Qt inter-process communication-shared memory

Insert picture description here

Description

setkey: Set the key, the key is the identifier used by the Qt application to identify the shared memory segment.
create: create shared memory space
lock/unlock: lock and unlock
attach: bind the process to shared memory
isAttached: determine whether to bind
detach: unbind

Code

#include "widget.h"
#include "ui_widget.h"
#include <QBuffer>
#include <QTextStream>
#include <QtDebug>

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);
}

Source download: https://download.csdn.net/download/sinat_33859977/12367396 .

Guess you like

Origin blog.csdn.net/sinat_33859977/article/details/105792787