Evgenii Legotckoi
Evgenii LegotckoiJan. 28, 2016, 11:11 a.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, 3:49 a.m.

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

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

Добрый день!

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

IscanderChe
  • Nov. 25, 2018, 1:24 p.m.

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

Comments

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

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 14, 2024, 8:07 p.m.
Circuit switching and packet data transmission networks Angioedema 1 priligy dapoxetine
i
innorwallNov. 14, 2024, 7:42 p.m.
How to Copy Files in Linux If only females relatives with DZ offspring were considered these percentages were 23 order priligy online uk
i
innorwallNov. 14, 2024, 5:09 p.m.
Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
i
innorwallNov. 14, 2024, 12:05 p.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, noon
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
Now discuss on the forum
i
innorwallNov. 14, 2024, 11:39 a.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 6:55 p.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 4:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks