且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跨平台方法可防止打开一个应用程序的多个实例

更新时间:2023-11-22 16:00:10

回答我的问题,因为在其他问题中没有找到其他人解决这个问题.

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

这可以使用 boost/interprocess/sync/named_mutex (我使用的是 boost 1.63 )以跨平台的方式实现

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

我在 Linux Windows 上都进行了测试,该实现阻止打开应用程序的第二个实例.

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

我发现的问题是,如果我在两个平台上都终止了该进程,则互斥锁不会被删除,因为未调用析构函数〜MyApplication .因此,只有在系统重新启动后,我才能再次运行该应用程序.

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);
}