B
B
BadCats2019-10-14 17:32:30
Qt
BadCats, 2019-10-14 17:32:30

Working with QSystemSemaphore and QSharedMemory?

This question is a follow-up to this one of mine: What is the relationship between c++ application multithreading and system level multithreading? (to understand the context)
- there, I provided a link: https://evileg.com/en/post/147/
- in the text of the above article, the author uses the following example:

clude "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();
}

- the code works, but only in main(), if you put it in a separate method, it doesn't work. Why is that?
It's time for clarifications: the method in which I put it all out - created it as non-static (tried to make it static) - is called by another static method - all this is for a static object.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2019-10-14
@gbg

Because class instances that are created by main() must exist for the entire duration of the program. And if you put them in another scope, they will be destroyed when they leave this scope.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question