forked from MatsuriDayo/nekoray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunGuard.hpp
107 lines (79 loc) · 2.38 KB
/
RunGuard.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#ifndef RUNGUARD_H
#define RUNGUARD_H
#include <QObject>
#include <QSharedMemory>
#include <QSystemSemaphore>
#include <QCryptographicHash>
class RunGuard {
public:
RunGuard(const QString &key);
~RunGuard();
bool isAnotherRunning(quint64 *data_out);
bool tryToRun(quint64 *data_in);
void release();
private:
const QString key;
const QString memLockKey;
const QString sharedmemKey;
QSharedMemory sharedMem;
QSystemSemaphore memLock;
Q_DISABLE_COPY(RunGuard)
};
namespace {
QString generateKeyHash(const QString &key, const QString &salt) {
QByteArray data;
data.append(key.toUtf8());
data.append(salt.toUtf8());
data = QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
return data;
}
} // namespace
RunGuard::RunGuard(const QString &key)
: key(key), memLockKey(generateKeyHash(key, "_memLockKey")), sharedmemKey(generateKeyHash(key, "_sharedmemKey")), sharedMem(sharedmemKey), memLock(memLockKey, 1) {
memLock.acquire();
{
QSharedMemory fix(sharedmemKey); // Fix for *nix: http://habrahabr.ru/post/173281/
fix.attach();
}
memLock.release();
}
RunGuard::~RunGuard() {
release();
}
bool RunGuard::isAnotherRunning(quint64 *data_out) {
if (sharedMem.isAttached()) {
return false;
}
memLock.acquire();
const bool isRunning = sharedMem.create(sizeof(quint64));if (!isRunning) {
if (data_out != nullptr) {
memcpy(data_out, sharedMem.data(), sizeof(quint64));
}
sharedMem.detach();
}
memLock.release();
return !isRunning;
}
bool RunGuard::tryToRun(quint64 *data_in) {
if (isAnotherRunning(nullptr)) // Extra check
return false;
memLock.acquire();
bool result = sharedMem.attach();
// if success attach, attach return false but the error is NoError, magic, love from qt6
// qt docs: If false is returned, call error() to determine which error occurred.
if (!result) if (sharedMem.error() == QSharedMemory::NoError) result = true;
if (result) memcpy(sharedMem.data(), data_in, sizeof(quint64));
memLock.release();
if (!result) {
release();
return false;
}
return true;
}
void RunGuard::release() {
memLock.acquire();
if (sharedMem.isAttached())
sharedMem.detach();
memLock.release();
}
#endif // RUNGUARD_H