Qt World Summit: Submit your Presentation

<Solved>QSharedMemory : Second process cannot attach

  • I have 2 processes.

    The first one creates a QSharedMemory, with a key.

    The creation is successful, as no error is returned.

    In the second process, I try and attach to the shared memory, having done setKey() with the same key name as the first process, and then try and attach() to the memory.

    The attach() fails. Using errorString() on the shared memory, the following string is returned :

    bq. QSharedMemory::handle: doesn’t exist

    This is how I create the Shared Memory for the first instance

    sharedMem = new QSharedMemory("GSASharedMemory");
    bool checkcreate = sharedMem->create(size);
    if (!checkcreate)
    Logger::WriteLog("Instance 1 : Cannot create shared memory" );
    QString tempstrcreate = sharedMem->errorString();
    tempstrcreate.prepend("Instance 1:");

    bool checkattach = sharedMem->isAttached();
     Logger::WriteLog("Instance 1 : memory created and attached" );
    QString temp1 = "creating mutex with:";


    This works fine. So the memory is created and is attached to.
    Next, while this is running...

    sharedMem = new QSharedMemory();
    bool attachMem = sharedMem->attach();
    Logger::WriteLog("Cannot attach to shared Memory" );
    QString errorstr = sharedMem->errorString();
    QBuffer buffer;
    QDataStream out(&buffer);
    out << P14TagName;
    size = buffer.size();
    /* bool checkMemoryCreation = sharedMem->create(size);
    if (!checkMemoryCreation) {
    Logger::WriteLog("Cannot create Shared Memory" );
    return 0;
    char to = (char)sharedMem->data();
    QString totemp = QString::fromUtf8(to);
    const char *from = buffer.data().data();
    QString totemp1 = from;
    memcpy(to, from, qMin(sharedMem->size(), size));
    QString tempKey = sharedMem->key();
    tempKey.append(" ::Written name into shared Memory");

    The attach fails. And I get the aforementioned error.

    What could I be missing here? Kindly advise, thanks.

  • Lifetime Qt Champion

    It would be easier for us to help you if you show us the code you use to create/attach the QSharedMemory.

  • Updated. Kindly check and advise.

  • Lifetime Qt Champion

    Are you sure that the process that created the QSharedMemory is still running while your second process tries to attach it ?

  • Yes, the process that created the shared memory is still running when the second process tries to attach to it. No ambiguity there.

  • Anyone, please? This is driving me wild...

  • Solved. Stray detach() statement, which would detach the first process from the memory,before the second had a chance to attach to it, hence it couldn't find a handle to it.

  • Hi,

    I'm having the same issue.

    can you please post your solution?

Log in to reply