qt防止重复启动

通常我们的程序需要访问各种资源,如果同时起多份实例,造成资源争用,带来混乱。

因此需要一个方法保证任何时候只起一个实例。

在qt中可以借助共享内存来实现。

QSharedMemory有一个create方法,在qt帮助里这么描述:

bool QSharedMemory::create(int size, AccessMode mode = ReadWrite)

Creates a shared memory segment of size bytes with the key passed to the constructor, set with setKey() or set with setNativeKey(), then attaches to the new shared memory segment with the given access mode and returns true. If a shared memory segment identified by the key already exists, the attach operation is not performed and false is returned. When the return value is false, call error() to determine which error occurred.


经过亲测,三个系统有效。

    QApplication a(argc, argv);
    QSharedMemory singleton(a.applicationName());
    if(!singleton.create(1))
    {
        QMessageBox::warning(NULL, "Waring", "Program already running!");
        return false;
    }   

参考:  http://www.qtcn.org/bbs/read-htm-tid-58116.html


备注一下,在qt5.4.0、5.6.3、5.10.1上验证

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值