SingleApplication/singleapplication.cpp

182 lines
5.6 KiB
C++
Raw Normal View History

// The MIT License (MIT)
//
// Copyright (c) Itay Grudev 2015 - 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <QtCore/QTime>
#include <QtCore/QThread>
#include <QtCore/QDateTime>
2016-08-10 09:42:46 +08:00
#include <QtCore/QByteArray>
2016-05-05 02:59:07 +08:00
#include <QtCore/QSharedMemory>
#include "singleapplication.h"
2016-08-10 09:42:46 +08:00
#include "singleapplication_p.h"
2012-12-23 06:12:38 +08:00
/**
2015-02-27 03:19:38 +08:00
* @brief Constructor. Checks and fires up LocalServer or closes the program
* if another instance already exists
2012-12-23 06:12:38 +08:00
* @param argc
* @param argv
2016-08-10 09:42:46 +08:00
* @param {bool} allowSecondaryInstances
2012-12-23 06:12:38 +08:00
*/
2016-08-10 09:42:46 +08:00
SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSecondary, Options options, int timeout )
2016-05-05 04:05:59 +08:00
: app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) )
2012-12-23 06:12:38 +08:00
{
Q_D(SingleApplication);
2019-10-13 15:34:28 +08:00
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
// On Android and iOS since the library is not supported fallback to
// standard QApplication behaviour by simply returning at this point.
qWarning() << "SingleApplication is not supported on Android and iOS systems.";
return;
#endif
2016-08-10 09:42:46 +08:00
// Store the current mode of the program
d->options = options;
2016-05-05 02:59:07 +08:00
2016-08-10 09:42:46 +08:00
// Generating an application ID used for identifying the shared memory
// block and QLocalServer
d->genBlockServerName();
2012-12-23 06:12:38 +08:00
2016-08-10 09:42:46 +08:00
#ifdef Q_OS_UNIX
// By explicitly attaching it and then deleting it we make sure that the
// memory is deleted even after the process has crashed on Unix.
2016-08-10 09:42:46 +08:00
d->memory = new QSharedMemory( d->blockServerName );
d->memory->attach();
delete d->memory;
#endif
// Guarantee thread safe behaviour with a shared memory block.
2016-08-10 09:42:46 +08:00
d->memory = new QSharedMemory( d->blockServerName );
// Create a shared memory block
if( d->memory->create( sizeof( InstancesInfo ) ) ) {
// Initialize the shared memory block
d->memory->lock();
d->initializeMemoryBlock();
d->memory->unlock();
} else {
2016-05-05 02:59:07 +08:00
// Attempt to attach to the memory segment
if( ! d->memory->attach() ) {
qCritical() << "SingleApplication: Unable to attach to shared memory block.";
qCritical() << d->memory->errorString();
delete d;
::exit( EXIT_FAILURE );
}
}
InstancesInfo* inst = static_cast<InstancesInfo*>( d->memory->data() );
QTime time;
time.start();
// Make sure the shared memory block is initialised and in consistent state
while( true ) {
d->memory->lock();
if( d->blockChecksum() == inst->checksum ) break;
if( time.elapsed() > 5000 ) {
qWarning() << "SingleApplication: Shared memory block has been in an inconsistent state from more than 5s. Assuming primary instance failure.";
d->initializeMemoryBlock();
}
2016-05-05 02:59:07 +08:00
d->memory->unlock();
2016-05-05 02:59:07 +08:00
2018-12-01 00:08:31 +08:00
// Random sleep here limits the probability of a collision between two racing apps
qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() );
QThread::sleep( 8 + static_cast <unsigned long>( static_cast <float>( qrand() ) / RAND_MAX * 10 ) );
}
if( inst->primary == false) {
d->startPrimary();
d->memory->unlock();
return;
}
2016-05-05 02:59:07 +08:00
// Check if another instance can be started
if( allowSecondary ) {
inst->secondary += 1;
inst->checksum = d->blockChecksum();
d->instanceNumber = inst->secondary;
d->startSecondary();
if( d->options & Mode::SecondaryNotification ) {
d->connectToPrimary( timeout, SingleApplicationPrivate::SecondaryInstance );
2016-05-05 02:59:07 +08:00
}
d->memory->unlock();
return;
}
2016-05-05 02:59:07 +08:00
d->memory->unlock();
d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance );
delete d;
2016-08-10 09:42:46 +08:00
::exit( EXIT_SUCCESS );
2012-12-23 06:12:38 +08:00
}
/**
* @brief Destructor
2012-12-23 06:12:38 +08:00
*/
SingleApplication::~SingleApplication()
2012-12-23 06:12:38 +08:00
{
Q_D(SingleApplication);
2016-05-05 02:59:07 +08:00
delete d;
}
2016-05-05 02:59:07 +08:00
bool SingleApplication::isPrimary()
{
Q_D(SingleApplication);
2016-08-10 09:42:46 +08:00
return d->server != nullptr;
2016-05-05 02:59:07 +08:00
}
bool SingleApplication::isSecondary()
{
Q_D(SingleApplication);
2016-08-10 09:42:46 +08:00
return d->server == nullptr;
2012-12-23 06:12:38 +08:00
}
2016-08-10 09:42:46 +08:00
quint32 SingleApplication::instanceId()
2012-12-23 06:12:38 +08:00
{
Q_D(SingleApplication);
2016-08-10 09:42:46 +08:00
return d->instanceNumber;
}
qint64 SingleApplication::primaryPid()
{
Q_D(SingleApplication);
return d->primaryPid();
}
2016-08-10 09:42:46 +08:00
bool SingleApplication::sendMessage( QByteArray message, int timeout )
{
Q_D(SingleApplication);
// Nobody to connect to
if( isPrimary() ) return false;
// Make sure the socket is connected
d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect );
2016-08-10 09:42:46 +08:00
d->socket->write( message );
bool dataWritten = d->socket->waitForBytesWritten( timeout );
d->socket->flush();
2016-08-10 09:42:46 +08:00
return dataWritten;
2012-12-23 06:12:38 +08:00
}