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 <uniq id> 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
     * */
        QMessageBox msgBox;
        msgBox.setText("The application is already running.\n"
                       "Allowed to run only one instance of the application.");
        return 1;

    Widget w;

    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 <uniq id> and <uniq id2> 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>");

    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
        sharedMemory.create(1); // Otherwise allocate 1 byte of memory
        is_running = false;     // And determines that another instance is not running

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

    MainWindow w;

    return a.exec();


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.
Support the author Donate

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

Добрый день!

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

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


Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways


Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
June 5, 2020, 2:28 a.m.

Qt - Test 001. Signals and slots

  • Result:0points,
  • Rating points-10
June 3, 2020, 1:56 a.m.

C++ - Тест 003. Условия и циклы

  • Result:35points,
  • Rating points-10
June 2, 2020, 9:11 p.m.
Aleksej Pikenin

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
Last comments
June 5, 2020, 10:52 a.m.

Распознавание изображений на Python с помощью TensorFlow и Keras

Огромное спасибо за метериал, по-больше бы подобных статей (с подробным описанием работы и примерами применения) на тему современных технологий. Вопрос поразмышлять. На текущий момент реал…
June 5, 2020, 1:39 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

По-моему, смысла в этом нет особого. Если делегат будет игнорировать настройки таблицы, то это приведёт ещё к большему непониманию, что вообще происходит, для программиста, который после вас буд…
June 5, 2020, 1:34 a.m.

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Сижу, размышляю: можно ли переписать делегата так, чтобы независимо от настроек строк выделялись строки?
June 5, 2020, 1:31 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Понятно. Я не обратил внимания на то, что там было в старом коде по настройкам строк :)
Now discuss on the forum
June 5, 2020, 6:13 a.m.

Фильтр для QtableView sql

Добрый день. Для такой фильтрации необходимо использовать QSortFilterProxyModel. В оффдоках есть хороший пример.
June 4, 2020, 2:46 a.m.
Mihail A

Qt- C++ QTableView подсветить строку

June 3, 2020, 1:49 a.m.

Можно ли сделать в QML таблицу как в Excel?

edi-tableview - нашел пока такое выглядит коряво, посмотрим что можно сделать
June 2, 2020, 2:46 a.m.
Evgenij Legotskoj

Медиа файлы Google Firebase

Картинки можете попробовать сжимать через QPixmap, там есть возможность установки scaleFactor, через него можете устанавливать нужные параметры. А что касается конвертации видео, то лучше п…
June 2, 2020, 2:01 a.m.
Evgenij Legotskoj

Перехват обращения к локальным файлам QWebEngineView

В вашем случае вполне адекватное решение. Так сказать меньше зло. В противном случае пришлось бы очень много переписывать и перепиливать.
© EVILEG 2015-2020
Recommend hosting TIMEWEB