Qt: single instance application with QSharedMemory
I have looked at several examples of creating a single instance of an application, and they all used the create () and attach () methods of QSharedMemory. Why do they need attach ()?
This looks great:
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;
}
In my understanding of the documentation. That should be enough.
One example might be: http://developer.nokia.com/community/wiki/Run_only_one_instance_of_a_Qt_application
source to share
They need attach()
, because it create()
can fail for other reasons, that the segment already exists. For example, the system may be running out of resources or the creation of a shared memory segment may be disabled for your application (eg SELinux). In this case, it create()
will return false, but error()
return a different error code (for example QSharedMemory::OutOfResources
), and you will not be able to find out that the segment already exists, but will attach()
detect it.
source to share
I am testing the minimal case on a Linux distribution:
#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 assume, the call create
seems to be sufficient for a presence error to occur. In my opinion, it attach
is only called when the second process wants to access the already created shared memory. But this is not the purpose of protecting one application.
source to share