跨平台方法可防止打开一个应用程序的多个实例 [英] Cross platform way to prevent opening multiple instances of an application

查看:74
本文介绍了跨平台方法可防止打开一个应用程序的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些问题如何阻止运行两个实例如何在C或C ++中创建单个实例应用程序>防止我的多个实例应用程序解决如何专门针对平台( Windows Linux )打开同一应用程序的多个实例.

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 application address how to prevent opening multiple instances of the same application for a platform specifically (Windows, Linux).

是否有跨平台的方法来实现这一目标?

Is there a cross platform way to achieve this?

推荐答案

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

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

这篇关于跨平台方法可防止打开一个应用程序的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆