Zingam
Zingam

Reputation: 4626

Qt: Single instance application with QSharedMemory

I looked up several examples how to create a single instance application and they all used create() and attach() methods of QSharedMemory. Why do they need attach()?

This seems to work perfectly:

bool SingleInstanceApplication::useSharedMemory()
{
    _sharedMemory.setKey(_uniqueKey);

    // If shared memory is created and attached successfuly,
    // no other application instace is running
    bool hasNoPreviousInstance = _sharedMemory.create(1);

    return !hasNoPreviousInstance;
}

According to my understanding of the documentation. This has to be enough.

One example would be: http://developer.nokia.com/community/wiki/Run_only_one_instance_of_a_Qt_application

Upvotes: 2

Views: 2206

Answers (2)

George Y.
George Y.

Reputation: 11769

They need attach() because create() may fail for other reasons that the segment already exists. For example the system may be out of resources, or a shared memory segment creation is disabled for your application (by SELinux for example). In this case create() will return false but error() will return a different error code (such as QSharedMemory::OutOfResources) and you won't be able to find out that a segment already exists, while attach() would find it out.

Upvotes: 1

epsilon
epsilon

Reputation: 2969

I test a minimal case on a Linux distro:

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

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    const char* MEM_KEY = "42";

    QSharedMemory sharedMem(MEM_KEY);

    if (sharedMem.create(1024)) {
        qDebug() << "Create shared memory";
    } else {
        if (sharedMem.error() == QSharedMemory::AlreadyExists) {
            qWarning() << "Already create. Exiting process";
            return 1;
        } else {
             // handle other possible errors
        }
    }
    return a.exec();
}

As you suggest, a call to create seems enough to make the attended error occur. In my understanding, attach is only called when a second process want to access an already created shared memory. But, that's not the purpose of a single application guard.

Upvotes: 0

Related Questions