How to make a loner application using Qt5 + for Windows (xp, 7, 8, 10)? That it was impossible to start two copies at the same time.
1 answer
Lock file
The file will be deleted automatically.
Each user can run his version.
#include <QString> #include <QLockFile> #include <QDir> #include <QMessageBox> QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/<unique identifier>.lock"); if(!lockFile.tryLock(100)){ QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("You already have this app running." "\r\nOnly one instance is allowed."); msgBox.exec(); return 1; } Semaphores and shared memory
Unique instance of the application on the whole machine
QSystemSemaphore sema("<unique identifier>", 1); sema.acquire(); #ifndef Q_OS_WIN32 // в Unix разделяемая память не чистится при креше // Очищаем, если осталась от предыдущих запусков QSharedMemory nix_fix_shmem("<unique identifier 2>"); if(nix_fix_shmem.attach()){ nix_fix_shmem.detach(); } #endif QSharedMemory shmem("<unique identifier 2>"); bool is_running; if (shmem.attach()){ is_running = true; }else{ shmem.create(1); is_running = false; } sema.release(); if(is_running){ QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("You already have this app running." "\r\nOnly one instance is allowed."); msgBox.exec(); return 1; } |