"unable to set key on lock" while attaching memory with native key in qt

703 views Asked by At

I'm trying to learn how to share memory between Qt and Non-Qt application while having read-write access from both. For now I'm trying to create and then attach already created memory in Qt using native key. While the program can successfully create shared memory segment, it can't access it during the next launch. How can I fix this? Is there a way to attach shared memory segment using only native key?

#include <QCoreApplication>
#include <QDebug>
#include <QSharedMemory>

#include <sys/shm.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "PID: " << getpid();

    QSharedMemory *mem = new(QSharedMemory);
    mem->setNativeKey("foobar");
    if (!mem->create(3072, QSharedMemory::ReadWrite))
    {
        qDebug() << "Create fail:" << mem->errorString();
        qDebug() << "trying to detach:" << mem->detach();
        if (mem->attach())
        {
            qDebug() << "Attached succesfully";
        }
        else
        {
            qDebug() << "Attach fail:" << mem->errorString() << ", error:" << mem->error();
        }
    }
    else
        qDebug() << "Memory created successfully: ";
    qDebug() << "nativeKey=" << mem->nativeKey() << ", key=" << mem->key();
    qDebug() << "Waiting for input";
    getchar();
    // return a.exec();
    return 0;
}

First launch: works as expected, the key is reset as nativeKey is set.

PID:  10989
Memory created successfully: 
nativeKey= "foobar" , key= ""
Waiting for input

Second launch: trying to create throws an error as expected, trying to detach also throws an error as expected (as it's not attached) but when trying to attach the memory there's another unexpected error.

PID:  10992
Create fail: "QSharedMemory::create: already exists"
trying to detach: false
Attach fail: "QSharedMemoryPrivate::initKey: unable to set key on lock" , error: 3
nativeKey= "foobar" , key= ""

Error 3 (from Qt documentation):

The operation failed because of an invalid key.

I don't know what's wrong with my nativeKey.

0

There are 0 answers