I am trying to write a SingleApplication
class that will only allow one instance of the program to be running. I am implementing this using QSharedMemory
The program works fine, unless I use a key with the value "42"
. Is there something wrong I am doing? Is this undefined behavior?
Main.cpp
int main(int argc, char *argv[])
{
//QApplication a(argc, argv);
SingleApplication a(argc, argv, "42"); //Does not work with '42'. Will work for any other value.
MainWindow w;
w.show();
return a.exec();
}
SingleApplication.h
class SingleApplication : public QApplication
{
Q_OBJECT
public:
SingleApplication(int &argc, char *argv[], const QString uniqueKey);
bool alreadyExists() const{ return bAlreadyExists; }
bool isMasterApp() const { return !alreadyExists(); }
bool sendMessage(const QString &message);
public slots:
//void checkForMessages();
signals:
//void messageAvailable(const QStringList& messages);
private:
bool bAlreadyExists;
QSharedMemory sharedMemory;
};
SingleApplication.cpp
SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv){
sharedMemory.setKey(uniqueKey);
//Create if one does not exist already
if(sharedMemory.create(5000))
{
qDebug() << "Created!";
bAlreadyExists = false;
}
else{
if(sharedMemory.error() == QSharedMemory::AlreadyExists){
qWarning() << "Program is already running!";
}
}
}
I would drop the whole own single application concept implemented by you from scratch personally. The qt-solutions repository has contained the
QtSingleApplication
class which was ported to Qt 5, too. You ought to be able to use that. There is little to no point in reinventing the wheel in my humble opinion.Should you still insist on doing it on your own, while your idea seems to be a little strange at first about passing the key to the constructor and not to manage that inside the class transparently, this could be a workaround for your case to make the solution more robust:
Disclaimer: this is just pseudo code and I have never tested it, actually, not even tried to compile it myself!