GrabBag/AppUtils/AppCommon/Inc/SingleInstanceManager.h

61 lines
1.6 KiB
C++

#ifndef SINGLEINSTANCEMANAGER_H
#define SINGLEINSTANCEMANAGER_H
#include <QString>
#include <QSharedMemory>
#include <QSystemSemaphore>
#include <memory>
/**
* @brief 单例运行管理器
*
* 确保应用程序只能运行一个实例
* 使用共享内存和系统信号量实现跨进程的单例检查
*
* 用法:
* @code
* SingleInstanceManager manager("MyApp");
* if (manager.isAnotherInstanceRunning()) {
* QMessageBox::information(nullptr, "应用程序已运行", "应用程序已经在运行中!");
* return 0;
* }
* @endcode
*/
class SingleInstanceManager
{
public:
/**
* @brief 构造函数
* @param appKey 应用程序唯一标识符(建议使用应用程序名称)
*/
explicit SingleInstanceManager(const QString& appKey);
/**
* @brief 析构函数,自动释放资源
*/
~SingleInstanceManager();
/**
* @brief 检查是否已有其他实例在运行
* @return true: 已有实例在运行, false: 当前是唯一实例
*/
bool isAnotherInstanceRunning() const;
/**
* @brief 释放单例锁(通常在析构时自动调用,也可以手动调用)
*/
void release();
private:
QString m_appKey;
std::unique_ptr<QSystemSemaphore> m_semaphore;
std::unique_ptr<QSharedMemory> m_sharedMemory;
bool m_isRunning;
// 禁止拷贝和赋值
SingleInstanceManager(const SingleInstanceManager&) = delete;
SingleInstanceManager& operator=(const SingleInstanceManager&) = delete;
};
#endif // SINGLEINSTANCEMANAGER_H