在項目開發過程中,有時候一個程序在一台機器上只允許運行一個程序,因此需要用代碼來控制實現,
用到的技術是共享內存和信號量
具體代碼實現如下:
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 }