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