diff --git a/singleapplication.cpp b/singleapplication.cpp index 340519a..cf35adb 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -26,9 +26,36 @@ #include #include +#ifdef Q_OS_UNIX +#include +#include +#endif +#ifdef Q_OS_WIN +#include +#endif + #include "singleapplication.h" #include "singleapplication_p.h" +static bool isProcessRunning( qint64 pid ) +{ + if ( pid <= 0 ) + return false; + +#ifdef Q_OS_UNIX + return kill( static_cast( pid ), 0 ) == 0 || errno != ESRCH; +#endif +#ifdef Q_OS_WIN + HANDLE hProcess = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, static_cast( pid ) ); + if ( hProcess == NULL ) + return false; + DWORD exitCode; + bool running = GetExitCodeProcess( hProcess, &exitCode ) && exitCode == STILL_ACTIVE; + CloseHandle( hProcess ); + return running; +#endif +} + /** * @brief Constructor. Checks and fires up LocalServer or closes the program * if another instance already exists @@ -138,6 +165,13 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda } } + // If the recorded primary PID is no longer running (e.g. force-killed), + // take over as the primary instance + if( inst->primary && !isProcessRunning( inst->primaryPid ) ){ + qWarning() << "SingleApplication: Primary instance (PID" << inst->primaryPid << ") is no longer running. Taking over."; + d->initializeMemoryBlock(); + } + if( inst->primary == false ){ d->startPrimary(); if( ! d->memory->unlock() ){