forked from bablosoft/BAS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleapplication.cpp
More file actions
88 lines (66 loc) · 1.99 KB
/
singleapplication.cpp
File metadata and controls
88 lines (66 loc) · 1.99 KB
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
#include <QTimer>
#include <QByteArray>
#include "singleapplication.h"
SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv)
{
sharedMemory.setKey(uniqueKey);
// when can create it only if it doesn't exist
if (sharedMemory.create(5000))
{
sharedMemory.lock();
*(char*)sharedMemory.data() = '\0';
sharedMemory.unlock();
bAlreadyExists = false;
// start checking for messages of other instances.
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(checkForMessage()));
timer->start(200);
}
// it exits, so we can attach it?!
else if (sharedMemory.attach()){
bAlreadyExists = true;
}
else{
// error
}
}
// public slots.
void SingleApplication::checkForMessage()
{
QStringList arguments;
sharedMemory.lock();
char *from = (char*)sharedMemory.data();
while(*from != '\0'){
int sizeToRead = int(*from);
++from;
QByteArray byteArray = QByteArray(from, sizeToRead);
byteArray[sizeToRead] = '\0';
from += sizeToRead;
arguments << QString::fromUtf8(byteArray.constData());
}
*(char*)sharedMemory.data() = '\0';
sharedMemory.unlock();
if(arguments.size()) emit messageAvailable( arguments );
}
// public functions.
bool SingleApplication::sendMessage(const QString &message)
{
//we cannot send mess if we are master process!
if (isMasterApp()){
return false;
}
QByteArray byteArray;
byteArray.append(char(message.size()));
byteArray.append(message.toUtf8());
byteArray.append('\0');
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
while(*to != '\0'){
int sizeToRead = int(*to);
to += sizeToRead + 1;
}
const char *from = byteArray.data();
memcpy(to, from, qMin(sharedMemory.size(), byteArray.size()));
sharedMemory.unlock();
return true;
}