From 254b4570f7486fab736c205fbabc172dd01d0d19 Mon Sep 17 00:00:00 2001 From: ouuan Date: Sat, 1 Feb 2020 17:20:21 +0800 Subject: [PATCH] feat: Add a function to check if the instance is the only instance The function: bool SingleApplication::isSingleInstance() Returns if the instance is the only running instance. It was hard to check the number of running instances after a crash, so this is an alternative solution for itay-grudev#89. It uses a trick: the shared memory will be released after the last instance detaches from it. --- README.md | 7 +++++++ singleapplication.cpp | 25 +++++++++++++++++++++++++ singleapplication.h | 6 ++++++ 3 files changed, 38 insertions(+) diff --git a/README.md b/README.md index fa60057..2655a9e 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,13 @@ Returns if the instance is a secondary instance. --- +```cpp +bool SingleApplication::isSingleInstance() +``` +Returns if the instance is the only running instance. + +--- + ```cpp quint32 SingleApplication::instanceId() ``` diff --git a/singleapplication.cpp b/singleapplication.cpp index 8ff8747..61f8c5f 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -160,6 +160,31 @@ bool SingleApplication::isSecondary() return d->server == nullptr; } +bool SingleApplication::isSingleInstance() +{ + Q_D(SingleApplication); + + InstancesInfo backup = *static_cast( d->memory->data() ); + + d->memory->detach(); + + if ( d->memory->create( sizeof( InstancesInfo ) ) ) { + d->memory->lock(); + *static_cast( d->memory->data() ) = backup; + d->memory->unlock(); + return true; + } + + if( ! d->memory->attach() ) { + qCritical() << "SingleApplication: Unable to attach to shared memory block."; + qCritical() << d->memory->errorString(); + delete d; + ::exit( EXIT_FAILURE ); + } + + return false; +} + quint32 SingleApplication::instanceId() { Q_D(SingleApplication); diff --git a/singleapplication.h b/singleapplication.h index cb50597..46afec2 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -100,6 +100,12 @@ class SingleApplication : public QAPPLICATION_CLASS */ bool isSecondary(); + /** + * @brief Check if the instance is the only running instance. + * @returns {bool} + */ + bool isSingleInstance(); + /** * @brief Returns a unique identifier for the current instance * @returns {qint32}