This repository has been archived by the owner on Oct 19, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Code to make sure a single instance is running
- Loading branch information
Showing
3 changed files
with
67 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters