forked from jahnf/Projecteur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runguard.cc
71 lines (59 loc) · 1.34 KB
/
runguard.cc
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
#include "runguard.h"
#include <QCryptographicHash>
namespace {
QString generateKeyHash(const QString& key, const QString& salt)
{
const QByteArray data(key.toUtf8().append(salt.toUtf8()));
return QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
}
}
RunGuard::RunGuard( const QString& key )
: m_key(key)
, m_memLockKey(generateKeyHash(key, "_memLockKey"))
, m_sharedmemKey(generateKeyHash(key, "_sharedmemKey"))
, m_sharedMem(m_sharedmemKey)
, m_memLock(m_memLockKey, 1)
{
m_memLock.acquire();
{
QSharedMemory fix(m_sharedmemKey); // Fix for *nix: http://habrahabr.ru/post/173281/
fix.attach();
}
m_memLock.release();
}
RunGuard::~RunGuard()
{
release();
}
bool RunGuard::isAnotherRunning()
{
if (m_sharedMem.isAttached())
return false;
m_memLock.acquire();
const bool isRunning = m_sharedMem.attach();
if (isRunning)
m_sharedMem.detach();
m_memLock.release();
return isRunning;
}
bool RunGuard::tryToRun()
{
if (isAnotherRunning()) // Extra check
return false;
m_memLock.acquire();
const bool result = m_sharedMem.create(sizeof(quint64));
m_memLock.release();
if (!result)
{
release();
return false;
}
return true;
}
void RunGuard::release()
{
m_memLock.acquire();
if (m_sharedMem.isAttached())
m_sharedMem.detach();
m_memLock.release();
}