zl程序教程

您现在的位置是:首页 >  工具

当前栏目

【Qt】通过共享内存实现应用程序的单实例检查

Qt实例应用程序 实现 通过 检查 共享内存
2023-09-14 09:12:47 时间

【Qt】通过共享内存实现应用程序的单实例检查

1、背景

在开发Qt程序的时候,我们往往不希望一台计算机上同一个程序被多次打开,即一台计算机上有且只有一个应用程序实例存在。
应用程序的单例化,有三种方式:分别通过共享内存、QtSingleApplication、文件锁实现。

本博客通过共享内存的方式,来实现应用程序单例化检查。

2、示例

使用共享内存,当第2个进程启动时,判断共享的内存区数据是否建立。
注意:Linux操作系统当在程序发生崩溃时,可能会出现未及时清除共享区数据,导致程序不能正常启动。

main.cpp文本内容如下:

// main.cpp
#include <QCoreApplication>
#include <QtCore/QSharedMemory>
#include <QDebug>


// "假设单个实例"函数用于判断是否只有一个实例在运行
bool isSingleInstance(const char* shared_memory_name)
{
    bool result;
    // shared_memory_name即共享内存的名称,示例:yus
    static QSharedMemory shared(shared_memory_name); //引入头文件 #include <QtCore/QSharedMemory>
    // 判断共享内存是否被占用
    if (shared.attach())
    {
        result=false;
    }
    else
    {
       result=true;
       shared.create(1); // 占用共享内存
    }
    return result;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<QString::fromLocal8Bit("[INFO] 程序开始运行... ...");

    // ---------   应用程序单例检查   --------- //
    // 一台计算机上被设计仅允许一个程序实例运行
    if(!isSingleInstance("Only_one_allowed.app"))
    {
        qDebug()<<QString::fromLocal8Bit("[warning] 已有程序正在运行,不允许再次运行!");
    return -1;
    }
    // ------------------------------------- //

    qDebug()<<QString::fromLocal8Bit("[INFO] 程序进入事件循环... ...");

    return a.exec();//进入事件循环
}

untitled.pro文件如下:

QT += core
QT -= gui

CONFIG += c++11

TARGET = jn10010537
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

3、运行

当程序运行一个实例后,再次运行则会被检测到重复运行,如下:
在这里插入图片描述