Share multiple segment with QSharedMemory



  • Hi every body

    i want to use QSharedMemory to share data between 2 applications using it for sharing one segment works perfectly but when i try 2 share more than one i have access just to the last one

    this my code

    sharedMemroy.cpp in the first application

    @
    void SharedMemory::loadIntoSharedMem(QString memoryKey,QString &data)
    {
    sharedMem.setKey(memoryKey);
    if (sharedMem.isAttached())
    {
    sharedMem.detach();
    }
    if( data.length())
    {
    // load into shared memory
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << data;
    int size = buffer.size();

         if (!sharedMem.create(size)) {
             qDebug()<<"Unable to create shared memory segment."<<sharedMem.isAttached()<<" "<<sharedMem.error();
    
         }
    
         sharedMem.lock();
         char *to = (char*)sharedMem.data();
         const char *from = buffer.data().data();
         memcpy(to, from, qMin(sharedMem.size(), size));
         sharedMem.unlock();
        }
    else
        {
          qDebug()<< "no data to share"
        }
    
    }
    

    @

    and in main

    @
    SharedMemory sh;
    sh.loadIntoSharedMem("memo1",data1 );
    sh.loadIntoSharedMem("memo2",data2 );
    sh.loadIntoSharedMem("memo3",data3 );
    @

    and on showSharedData.cpp in the seconde application

    @
    QString ShowSharedMemory::loadFromSharedMem(QString memoryKey)
    {
    sharedMem.setKey(memoryKey);
    if (!sharedMem.attach())
    {
    qDebug()<<"Unable to load!";
    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();
    
    sharedMem.detach();
    return text;
    

    }
    @

    and in main

    @
    data1=showMemory.loadFromSharedMem("memo1");
    data2=showMemory.loadFromSharedMem("memo2");
    data3=showMemory.loadFromSharedMem("memo3");
    @

    thanks for your help



  • in the first source code I see shared memory key as 'mem' etc. In the reader code you specifying the sharedmemory keys as dddd etc. Why are giving different keys for reader and writer ? It need to be same key for both reader and writer.



  • @dheerendra thanks aswring
    yes sur it was just a mistake of copy/past :p
    but on the code there are the same


  • Lifetime Qt Champion

    Hi,

    If I remember the QSharedMemory mechanism correctly and following your code, you are creating and destroying the two first and only the third lives long enough to actually share some data



  • If possible can you share you entire code. I can look and share you the right solution.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.