日志
保证仅一个程序运行
2019-09-16 10:27
/*singleapplication.h */
#ifndef SINGLEAPPLICATION_H #define SINGLEAPPLICATION_H #include <QApplication> #include <QSharedMemory> class SingleApplication : public QApplication { Q_OBJECT public: SingleApplication(int &argc, char *argv[], const QString uniqueKey); bool isRunning(); bool sendMessage(const QString &message); public slots: void checkForMessage(); signals: void messageAvailable(QString message); private: bool _isRunning; QSharedMemory sharedMemory; }; #endif // SINGLEAPPLICATION_H /*singleapplication.cpp */ #include "singleapplication.h" #include <QTimer> #include <QByteArray> SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv) { sharedMemory.setKey(uniqueKey); if (sharedMemory.attach()) _isRunning = true; else { _isRunning = false; // attach data to shared memory. QByteArray byteArray("0"); // default value to note that no message is available. if (!sharedMemory.create(byteArray.size())) { qDebug("Unable to create single instance."); return; } sharedMemory.lock(); char *to = (char*)sharedMemory.data(); const char *from = byteArray.data(); memcpy(to, from, qMin(sharedMemory.size(), byteArray.size())); sharedMemory.unlock(); // start checking for messages of other instances. QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(checkForMessage())); timer->start(1000); } } // public slots. void SingleApplication::checkForMessage() { sharedMemory.lock(); QByteArray byteArray = QByteArray((char*)sharedMemory.constData(), sharedMemory.size()); sharedMemory.unlock(); if (byteArray.left(1) == "0") return; byteArray.remove(0, 1); QString message = QString::fromUtf8(byteArray.constData()); emit messageAvailable(message); // remove message from shared memory. byteArray = "0"; sharedMemory.lock(); char *to = (char*)sharedMemory.data(); const char *from = byteArray.data(); memcpy(to, from, qMin(sharedMemory.size(), byteArray.size())); sharedMemory.unlock(); } // public functions. bool SingleApplication::isRunning() { return _isRunning; } bool SingleApplication::sendMessage(const QString &message) { if (!_isRunning) return false; QByteArray byteArray("1"); byteArray.append(message.toUtf8()); byteArray.append('/0'); // < should be as char here, not a string! sharedMemory.lock(); char *to = (char*)sharedMemory.data(); const char *from = byteArray.data(); memcpy(to, from, qMin(sharedMemory.size(), byteArray.size())); sharedMemory.unlock(); return true; } /* main.cpp */ int main(int argc, char *argv[]) { // QApplication a(argc, argv); SingleApplication a(argc, argv, "some unique key string"); if (a.isRunning()) { QMessageBox::information(NULL, "提示", "已经有一个升级设备在运行!","确定"); return 0; } MainWindow w; w.show(); return a.exec(); } |