Skip to content

Commit

Permalink
feat: Add a function to check if the instance is the only instance
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ouuan committed Feb 1, 2020
1 parent 473dfae commit 254b457
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
```
Expand Down
25 changes: 25 additions & 0 deletions singleapplication.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,31 @@ bool SingleApplication::isSecondary()
return d->server == nullptr;
}

bool SingleApplication::isSingleInstance()
{
Q_D(SingleApplication);

InstancesInfo backup = *static_cast<InstancesInfo*>( d->memory->data() );

d->memory->detach();

if ( d->memory->create( sizeof( InstancesInfo ) ) ) {
d->memory->lock();
*static_cast<InstancesInfo*>( 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);
Expand Down
6 changes: 6 additions & 0 deletions singleapplication.h
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down

0 comments on commit 254b457

Please sign in to comment.