Evgenii Legotckoi
Evgenii LegotckoiJan. 28, 2016, 10:11 p.m.

Qt/C++ - Lesson 043. Qt Single Application - Start only one instance of application

Permission to run only one instance of the application may be necessary to limit the problems with memory leaks, or to eliminate possible problems with the competition between two instances of an application for some resources, files, SQLite database, etc. Or if, in principle, the application requires only one copy is used by the user.

Two methods can be used to solve this problem:

  • Using QLockFile - when a temporary file is created, which is destroyed when the application is closed. Thus at the second instance of the application starts happening on the existence of the file and check if the file already created one open application instance, the second instance is automatically closed;
  • Using QSystemSemaphore and QSharedMemory - in this case creates a shared memory segment and tries to connect it to an existing segment with a unique identifier. If the connection attempt is successful, then one instance of the application has already been created. Accordingly, we inform the user about it and close the application. If the connection attempt is unsuccessful, then we select create memory segment for the application and run the first instance.

The rest of the code will not go beyond main.cpp.

Single application using QLockFile

In the following code in the folder for temporary files created during application startup Lock File, in the case of an unsuccessful attempt to create a Lock File, the program assumes that is already open one instance of the application, notify the user and closes.

Note. Replace on your ID.

#include "widget.h"
#include <QApplication>
#include <QLockFile>
#include <QDir>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLockFile lockFile(QDir::temp().absoluteFilePath("<uniq id>.lock"));

    /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds, 
     * then there is a Lock File already created by another process. 
     / Therefore, we throw a warning and close the program
     * */
    if(!lockFile.tryLock(100)){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The application is already running.\n"
                       "Allowed to run only one instance of the application.");
        msgBox.exec();
        return 1;
    }

    Widget w;
    w.show();

    return a.exec();
}

Single application using QSystemSemaphore and QSharedMemory

In a first variant, it is given a simple and convenient solution to the problem by limiting the number of running instances of Qt applications. But the decision on QLockFile has disadvantages in the sense that there may be a problem with the permissions of the user. And also, if you want to limit, run a single instance of the program for the entire computer, not the differences, how many user sessions can be run on it, then use QLockFile also does not provide this capability.

QSharedMemory the contrary is shared for all users at the same time working at a computer. Therefore, if one of your users to run the program, the latter will not be able to run it.

But in this case, it is necessary not to forget about the differences in the shared memory by the various platforms. In the case with Windows , shared memory will be freed when a normal completion of the program, and at the end of the emergency. In the case of Linux/Unix in case of emergency when crashes memory will not be freed.

The semaphore code presented below is used to solve the problem of race in the case of the simultaneous launch of multiple instances of the same application. The semaphore is created with the meter, the maximum number of which is equal to 1. When lifting the semaphore, all other instances of the application does not have access to the shared memory and thus one copy of wholly owned resources. This copy checks for running another instance of the application by the presence of a shared memory segment identifier corresponding to the application. A copy of the shared memory segment was successfully launched and creates if not found information about another application instance. After that, the semaphore is lowered, allowing another instance of the application tried to run.

Note. Replace and on your ID.

#include "mainwindow.h"
#include <QApplication>
#include <QSystemSemaphore>
#include <QSharedMemory>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QSystemSemaphore semaphore("<uniq id>", 1);  // create semaphore
    semaphore.acquire(); // Raise the semaphore, barring other instances to work with shared memory

#ifndef Q_OS_WIN32
    // in linux / unix shared memory is not freed when the application terminates abnormally,
    // so you need to get rid of the garbage
    QSharedMemory nix_fix_shared_memory("<uniq id 2>");
    if(nix_fix_shared_memory.attach()){
        nix_fix_shared_memory.detach();
    }
#endif

    QSharedMemory sharedMemory("<uniq id 2>");  // Create a copy of the shared memory
    bool is_running;            // variable to test the already running application
    if (sharedMemory.attach())
    {                           // We are trying to attach a copy of the shared memory
                                // To an existing segment
        is_running = true;      // If successful, it determines that there is already a running instance
    }
    else
    {
        sharedMemory.create(1); // Otherwise allocate 1 byte of memory
        is_running = false;     // And determines that another instance is not running
    }
    semaphore.release();       

    // If you already run one instance of the application, then we inform the user about it
    // and complete the current instance of the application
    if (is_running)
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The application is already running.\n" 
                       "Allowed to run only one instance of the application.");
        msgBox.exec();
        return 1;
    }

    MainWindow w;
    w.show();

    return a.exec();
}

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

IscanderChe
  • Nov. 25, 2018, 2:49 p.m.

День добрый.
Подскажите, как с помощью этих примеров вместо вывода сообщения сделать активным окно запущенного экземпляра приложения?

Evgenii Legotckoi
  • Nov. 25, 2018, 11:20 p.m.

Добрый день!

С помощью API целевой системы придётся найти нужный процесс и открыть окно. Но придётся писать платформозависимый код. В случае Windows нужно смотреть, как с помощью WinAPI искать процессы и пытаться открыть их окна, если они есть. В случае Linux там ещё сложнее, или через XLib, или через DBus, но я не уверен, как именно это делается.

IscanderChe
  • Nov. 26, 2018, 12:24 a.m.

Понятно. Спасибо!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 8:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 26, 2023, 12:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 10:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 11:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 20, 2024, 1:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 10:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 6:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 8:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks