21 #include <QCoreApplication>
36 const char* getCurUsername()
38 return getenv(
"USERNAME");
41 const char* getCurUsername()
43 return getenv(
"USER");
49 auto* user = getCurUsername();
52 qWarning() <<
"Failed to get current username. Will use a global IPC.";
74 , globalMemory{getIpcKey()}
76 qRegisterMetaType<IPCEventHandler>(
"IPCEventHandler");
78 timer.setInterval(EVENT_TIMER_MS);
79 timer.setSingleShot(
true);
91 static std::mt19937 rng(std::chrono::high_resolution_clock::now().time_since_epoch().count());
92 std::uniform_int_distribution<uint64_t> distribution;
93 globalId = distribution(rng);
94 qDebug() <<
"Our global IPC ID is " << globalId;
95 if (globalMemory.create(
sizeof(IPCMemory))) {
96 if (globalMemory.lock()) {
97 IPCMemory* mem = global();
98 memset(mem, 0,
sizeof(IPCMemory));
99 mem->globalId = globalId;
100 mem->lastProcessed = time(
nullptr);
101 globalMemory.unlock();
103 qWarning() <<
"Couldn't lock to take ownership";
105 }
else if (globalMemory.attach()) {
106 qDebug() <<
"Attaching to the global shared memory";
108 qDebug() <<
"Failed to attach to the global shared memory, giving up. Error:"
109 << globalMemory.error();
119 qWarning() <<
"Failed to lock in ~IPC";
136 time_t
IPC::postEvent(
const QString& name,
const QByteArray& data, uint32_t dest)
138 QByteArray binName = name.toUtf8();
139 if (binName.length() >
static_cast<int32_t
>(
sizeof(
IPCEvent::name))) {
143 if (data.length() >
static_cast<int32_t
>(
sizeof(
IPCEvent::data))) {
148 qDebug() <<
"Failed to lock in postEvent()";
164 memcpy(evt->
name, binName.constData(), binName.length());
165 memcpy(evt->
data, data.constData(), data.length());
169 qDebug() <<
"postEvent " << name <<
"to" << dest;
183 qWarning() <<
"isCurrentOwner failed to lock, returning false";
204 if (difftime(
global()->lastProcessed, time) > 0) {
221 time_t start = time(
nullptr);
225 if (result || (timeout > 0 && difftime(time(
nullptr), start) >= timeout)) {
229 qApp->processEvents();
275 if (QThread::currentThread() == qApp->thread()) {
276 result = handler(arg);
278 QMetaObject::invokeMethod(
this,
"runEventHandler", Qt::BlockingQueuedConnection,
280 Q_ARG(
const QByteArray&, arg));
302 qDebug() <<
"Previous owner timed out, taking ownership" << mem->
globalId <<
"->"
313 QString name = QString::fromUtf8(evt->name);
317 qDebug() <<
"Processed event:" << name <<
"posted:" << evt->posted
318 <<
"accepted:" << evt->accepted;
319 if (evt->dest == 0) {
324 evt->processed = time(
nullptr);
327 evt->processed = time(
nullptr);
330 qDebug() <<
"Received event:" << name <<
"without handler";
347 qWarning() <<
"isCurrentOwnerNoLock failed to access the memory, returning false";
350 return (*
static_cast<const uint64_t*
>(data) ==
globalId);