在项目开发过程中,有时候一个程序在一台机器上只允许运行一个程序,因此需要用代码来控制实现,
用到的技术是共享内存和信号量
具体代码实现如下:
1 #include "mainwindow.h"
2
3 #include <QApplication>
4 #include <QSystemSemaphore>
5 #include <QSharedMemory>
6 #include <QDebug>
7
8
9
10 int main(int argc, char *argv[]) 11 { 12 //环境变量设置
13 QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); 14 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); 15
16 QApplication a(argc, argv); 17
18 //确保只运行一次
19 QSystemSemaphore sema("HuiGuo", 1, QSystemSemaphore::Open); 20 sema.acquire();//在临界区操作共享内存 SharedMemory
21
22 QSharedMemory mem("HuiGuoObject"); //全局对象名
23 bool bCreate = mem.create(1); 24 qDebug() << "bCreate=============" << bCreate; 25
26 if(bCreate) 27 { 28 //创建成功,说明之前没有程序在运行
29 qDebug() << "create shared memory success======"; 30 } 31 else
32 { 33 //创建失败,说明已经有一个程序在运行了。
34 qDebug() << "An instance has already been running======"; 35 sema.release();//如果是 Unix 系统,会自动释放。
36 return 0; 37 } 38
39 sema.release();//临界区
40
41 MainWindow w; 42 w.show(); 43 return a.exec(); 44 }