Skip to content
This repository has been archived by the owner on Oct 19, 2023. It is now read-only.

Commit

Permalink
Code to make sure a single instance is running
Browse files Browse the repository at this point in the history
  • Loading branch information
ltworf committed Aug 9, 2016
1 parent d3200a6 commit b73781f
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 2 deletions.
48 changes: 48 additions & 0 deletions singleinstance.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <QLockFile>
#include <QProcessEnvironment>

#include "singleinstance.h"

/**
* @brief filename
* @param key
* @param scope
* @return a fully qualified filename
*
* Generates an appropriate filename for the lock
*/
static QString filename(QString key, scope_t scope) {

QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString tmp = env.value("TEMP", "/tmp") + "/";
QString user = env.value("USER", "alfio");


QString r;
switch (scope) {
case SYSTEM:
r = tmp;
break;
case SESSION:
//TODO this will prevent trabucco to run in multiple sessions
r = env.value("XDG_RUNTIME_DIR", tmp + user) + "/";
break;
}
return r + key + ".lock";
}

/**
* @brief SingleInstance::unique
* @param key the unique name of the program
* @param scope wether it needs to be system-wide or session-wide
* @return true if this is the only instance
*
* Make sure that this instance is unique.
*/
bool SingleInstance::unique(QString key, scope_t scope) {
QLockFile* lock = new QLockFile(filename(key, scope));
bool r = lock->tryLock();
if (!r)
delete lock;
return r;
}
15 changes: 15 additions & 0 deletions singleinstance.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#ifndef SINGLEINSTANCE_H
#define SINGLEINSTANCE_H

typedef enum {
SYSTEM,
SESSION,
} scope_t;

class SingleInstance
{
public:
static bool unique(QString key, scope_t scope);
};

#endif // SINGLEINSTANCE_H
6 changes: 4 additions & 2 deletions trabucco.pro
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ CONFIG += c++11
LIBS += -lX11

SOURCES += main.cpp \
settings.cpp
settings.cpp \
singleinstance.cpp

RESOURCES += qml.qrc

Expand All @@ -18,7 +19,8 @@ QML_IMPORT_PATH =
include(deployment.pri)

HEADERS += \
settings.h
settings.h \
singleinstance.h

FORMS += \
settings.ui
Expand Down

0 comments on commit b73781f

Please sign in to comment.