應用程式單例
注1:最簡單辦法,建立系統核心物件(IPC中很多,如windows event/mutex...),檢查核心物件是否建立成功,如不成功app退出,成功繼續啟動。
注2:建立共享區,如
#pragma data_seg("flag_data")
int app_count = 0;
#pragma data_seg()
#pragma comment(linker,"/SECTION:flag_data,RWS")
app判斷app_count即可。
Qt共享記憶體計數方式(小題大做)
singleinstancesharedmemory.h
#ifndef SINGLEINSTANCESHAREDMEMORY_H #define SINGLEINSTANCESHAREDMEMORY_H #include <QSharedMemory> //Note: Call addRef first class SingleInstanceSharedMemory : public QSharedMemory { Q_OBJECT public: SingleInstanceSharedMemory(const QString &key, QObject *parent = nullptr); ~SingleInstanceSharedMemory(); <pre name="code" class="cpp"><pre name="code" class="cpp"> int addRef(); int releaseRef(); bool isRunning();
private:
<span style="font-family: Arial, Helvetica, sans-serif;">bool incrementIns();</span>
bool decrementIns();};#endif // SINGLEINSTANCESHAREDMEMORY_H
singleinstancesharedmemory.cpp#include "singleinstancesharedmemory.h" SingleInstanceSharedMemory::SingleInstanceSharedMemory(const QString &key, QObject *parent/* = nullptr*/) : QSharedMemory(key,parent) { } SingleInstanceSharedMemory::~SingleInstanceSharedMemory() { } bool SingleInstanceSharedMemory::decrementIns() { if(this->isAttached()) { lock(); char *data = (char*)this->data(); *data = '0'; unlock(); return true; } return false; } bool SingleInstanceSharedMemory::incrementIns() { if(this->isAttached()) { lock(); char *data = (char*)this->data(); *data = '1'; unlock(); return true; } return false; } bool SingleInstanceSharedMemory::isRunning() { if(this->isAttached()) { char ret; lock(); char *data = (char*)this->data(); ret = *data; unlock(); if ('1' == ret) { return true; } } return false; } int SingleInstanceSharedMemory::addRef() { if (!create(1)) { if (QSharedMemory::AlreadyExists == error()) { //SharedMemory has already existed if (attach()) { lock(); char data = *((char*)this->data()); unlock(); if ('1' == data) { return QSharedMemory::AlreadyExists; } } } } if(incrementIns()) { return QSharedMemory::NoError; } else { return QSharedMemory::UnknownError; } } int SingleInstanceSharedMemory::releaseRef() { if(decrementIns()) { return QSharedMemory::NoError; } else { return QSharedMemory::UnknownError; } }
程式啟動時:
SingleInstanceSharedMemory *share_memory = new SingleInstanceSharedMemory(QString("SingleInstanceApplication"));
if(QSharedMemory::AlreadyExists == share_memory->addRef())
{
//ShowAppMainWindow();
return 0;
}
如果有登出,可呼叫:share_memory->releaseRef()