Cross platform way to prevent opening multiple instances of an application

前端 未结 2 1856
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-28 18:00

These questions How to block running two instances of the same program? , How to create a single instance application in C or C++ and Preventing multiple instances of my applica

相关标签:
2条回答
  • 2021-01-28 18:36

    Answering my question, as I didn't find someone else addressing this in the other questions.

    This can be achieved in a cross platform way using boost/interprocess/sync/named_mutex (I used boost 1.63)

    I tested on both Linux and Windows and the implementation prevents opening a second instance of the application.

    The problem that I found is that if I kill the process (on both platforms), the mutex is not removed because the destructor ~MyApplication is not called. So only after system restart I will be able to run the application again.

    #include <boost/interprocess/sync/named_mutex.hpp>
    #include <iostream>
    
    class MyApplication
    {
    public:
        MyApplication() = default;
    
        ~MyApplication()
        {
            if (mLockedByThisInstance)
            {
                boost::interprocess::named_mutex::remove("myApplicationMutex");
            }
        }
    
        bool IsAlreadyRunning()
        {
            mLockedByThisInstance = mNamedMutex.try_lock();
    
            if (!mLockedByThisInstance)
            {
                return true;
            }
    
            return false;
        }
    
        int Run(int argc, char *argv[])
        {
            // Application main loop            
            return 0;
        }
    
    private:
        bool mLockedByThisInstance = false;
        boost::interprocess::named_mutex mNamedMutex{ boost::interprocess::open_or_create,
            "myApplicationMutex" };
    };
    
    int main(int argc, char *argv[])
    {
        MyApplication myApplication;
    
        if (myApplication.IsAlreadyRunning())
        {
            std::cout << "MyApplication is already running!\n";
            return 1;
        }
    
        return myApplication.Run(argc, argv);
    }
    
    0 讨论(0)
  • 2021-01-28 18:37

    This is not really a complete answer, but look into something like holding a specific file handle for exclusive access. You can use this like a mutex, but with the added benefit that the OS should "clean up" the handle on process termination automatically.

    I cannot speak to if this will work on Linux, but at least on Windows, this should let you achieve the same effect. Hope that helps.

    0 讨论(0)
提交回复
热议问题