Cross platform way to prevent opening multiple instances of an application

前端 未结 2 1860
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  猫巷女王i
    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 
    #include 
    
    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);
    }
    

提交回复
热议问题