在项目开发过程中,有时候一个程序在一台机器上只允许运行一个程序,因此需要用代码来控制实现,
用到的技术是共享内存和信号量
具体代码实现如下:
#include "mainwindow.h"
#include <QApplication>
#include <QSystemSemaphore>
#include <QSharedMemory>
#include <QDebug>
int main(int argc, char *argv[])
{
//环境变量设置
QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication a(argc, argv);
//确保只运行一次
QSystemSemaphore sema("HuiGuo", 1, QSystemSemaphore::Open);
sema.acquire();//在临界区操作共享内存 SharedMemory
QSharedMemory mem("HuiGuoObject"); //全局对象名
bool bCreate = mem.create(1);
qDebug() << "bCreate=============" << bCreate;
if(bCreate)
{
//创建成功,说明之前没有程序在运行
qDebug() << "create shared memory success======";
}
else
{
//创建失败,说明已经有一个程序在运行了。
qDebug() << "An instance has already been running======";
sema.release();//如果是 Unix 系统,会自动释放。
return 0;
}
sema.release();//临界区
MainWindow w;
w.show();
return a.exec();
}