前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使Qt程序只能运行一个实例的3种方法

使Qt程序只能运行一个实例的3种方法

作者头像
用户5807183
发布2019-09-03 11:16:13
3.4K0
发布2019-09-03 11:16:13
举报
文章被收录于专栏:Linux知识积累Linux知识积累

1. 共享内存的方法

Unix: QSharedMemory "owns" the shared memory segment. When the last thread or process that has an instance of QSharedMemory attached to a particular shared memory segment detaches from the segment by destroying its instance of QSharedMemory, the Unix kernel release the shared memory segment. But if that last thread or process crashes without running the QSharedMemory destructor, the shared memory segment survives the crash.

(据说这种方法在Linux系统下会有一个内存释放的问题,在某种情况下会引起程序的异常或崩溃)

代码语言:javascript
复制
// 确保只运行一次   

QSystemSemaphore sema("JAMKey",1,QSystemSemaphore::Open);   
sema.acquire();// 在临界区操作共享内存   SharedMemory   

QSharedMemory mem("SystemObject");// 全局对象名   
if (!mem.create(1))// 如果全局对象以存在则退出   
{   
    QMessageBox::information(0, MESSAGEBOXTXT,"An instance has already been running.");  

    sema.release();// 如果是 Unix 系统,会自动释放。   

    return 0;   
}   

sema.release();// 临界区   

2. 使用QLocalServer和QLocalSocket类

下面是自已的写的代码,主要是在运行第二实例的时候,有一个提示的作用:

1. 切换到当前程序,并将当前程序最大化显示到前面。

2.关闭当前程序的进程,打开新程序。

(注意:需要在你的.pro里加上QT += network)

头文件:
代码语言:javascript
复制
#ifndef PSA_USR_LOGIN_H  
#define PSA_USR_LOGIN_H  

#include <QDialog>  
#include <QTimeLine>  
#include <QLocalServer>  

#include "ui_DlgUsrLogin.h"  

#define PROCESS_SHOW        1  
#define PROCESS_RESTART     2  
#define PROCESS_STOP        3  

const QString PRO_SHOW      = "PRO_SHOW";  
const QString PRO_RESTART   = "PRO_RESTART";  
const QString PRO_STOP      = "PRO_STOP";  

class CUsrLogin : public QDialog  
{  
    Q_OBJECT  

public:  
    CUsrLogin(const QString& serverName, QWidget* parent = NULL);  
    virtual ~CUsrLogin();  

    int GetIndex() const;  
    bool InitServer();  

signals:  
    void sig_newOrder(const QString&);  

private slots:  
    void slot_ok();  
    void slot_cancel();  
    void slot_btnGroupClicked(int);  
    void slot_newConnection();  
    void slot_readyRead();  
    void slot_timeFinished();  

private:  
    int IsServerRun(const QString & servername);  

private:  
    Ui::DlgUsrLogin ui;  

    int mIndex;  
    QString mServerName;  
    QLocalServer* mpServer;  
    QTimeLine *mpTimeLine;  
};  

#endif  
源文件:
[cpp] view plain copy
#include "psa_usr_login.h"  
#include <QButtonGroup>  
#include <QLocalSocket>  

CUsrLogin::CUsrLogin( const QString& serverName, QWidget* parent /*= NULL*/ )  
    : QDialog(parent)  
    , mpServer(NULL)  
    , mpTimeLine(NULL)  
{  
    ui.setupUi(this);  

    mIndex = 1;  
    mServerName = serverName;  

    QButtonGroup* btnGroup = new QButtonGroup;  
    btnGroup->addButton(ui.btn_showCurPro,  PROCESS_SHOW);  
    btnGroup->addButton(ui.btn_openNewPro,  PROCESS_RESTART);  

    ui.progressBar->setVisible(false);  
    mpTimeLine = new QTimeLine(3000, this);  
    mpTimeLine->setFrameRange(0, 100);  
    connect(mpTimeLine, SIGNAL(frameChanged(int)), ui.progressBar, SLOT(setValue(int)));  
    connect(mpTimeLine, SIGNAL(finished()), this, SLOT(slot_timeFinished()));  

    connect(btnGroup, SIGNAL(buttonPressed(int)), this, SLOT(slot_btnGroupClicked(int)));  
    connect(ui.btn_ok, SIGNAL(clicked()), this, SLOT(slot_ok()));  
    connect(ui.btn_cancel, SIGNAL(clicked()), this, SLOT(slot_cancel()));  
}  

CUsrLogin::~CUsrLogin()  
{  
    if(mpServer)  
    {  
        QLocalServer::removeServer(mServerName);  
        delete mpServer;  
        mpServer = NULL;  
    }  

    if(mpTimeLine)  
    {  
        mpTimeLine->stop();  
        delete mpTimeLine;  
        mpTimeLine = NULL;  
    }  
}  

int CUsrLogin::GetIndex() const  
{  
    return mIndex;  
}  

void CUsrLogin::slot_ok()  
{  
    QLocalSocket ls;  
    ls.connectToServer(mServerName);  

    if (ls.waitForConnected())  
    {  
        switch(mIndex)  
        {  
        case PROCESS_SHOW:  
            {  
                char msg[25] = {0};  
                memcpy(msg, PRO_SHOW.toStdString().c_str(), PRO_SHOW.length());  
                ls.write(msg);  
                ls.waitForBytesWritten();  

                QDialog::accept();  
                break;  
            }  
        case PROCESS_RESTART:  
            {  
                char msg[25] = {0};  
                memcpy(msg, PRO_RESTART.toStdString().c_str(), PRO_RESTART.length());  
                ls.write(msg);  
                ls.waitForBytesWritten();  

                ui.progressBar->setVisible(true);  
                mpTimeLine->start();  
                break;  
            }  
        case PROCESS_STOP:  
            {  
                char msg[25] = {0};  
                memcpy(msg, PRO_STOP.toStdString().c_str(), PRO_STOP.length());  
                ls.write(msg);  
                ls.waitForBytesWritten();  

                QDialog::accept();  
                break;  
            }  
        default:  
            QDialog::accept();  
            break;  
        }  
    }  
}  

void CUsrLogin::slot_cancel()  
{  
    QDialog::reject();  
}  

void CUsrLogin::slot_btnGroupClicked( int idx)  
{  
    mIndex = idx;  
}  

void CUsrLogin::slot_readyRead()  
{  
    QLocalSocket *local = static_cast<QLocalSocket *>(sender());  
    if (!local)  
        return;  

    QTextStream in(local);  
    QString     readMsg;  

    readMsg = in.readAll();  

    emit sig_newOrder(readMsg);  
}  

// 判断是否有一个同名的服务器在运行  
int CUsrLogin::IsServerRun(const QString & servername)  
{          
    QLocalSocket ls;  
    ls.connectToServer(servername);  

    if (ls.waitForConnected(1000))   
    {  
        ls.disconnectFromServer();  
        ls.close();  
        return 1;  
    }  

    return 0;  
}  

bool CUsrLogin::InitServer()  
{  
    if (!IsServerRun(mServerName))  
    {  
        mpServer = new QLocalServer;  
        QLocalServer::removeServer(mServerName);  

        mpServer->listen(mServerName);  
        connect(mpServer, SIGNAL(newConnection()), this, SLOT(slot_newConnection()));  

        return true;  
    }  

    return false;  
}  

void CUsrLogin::slot_newConnection()  
{  
    QLocalSocket *newsocket = mpServer->nextPendingConnection();  
    connect(newsocket, SIGNAL(readyRead()), this, SLOT(slot_readyRead()));  
}  

void CUsrLogin::slot_timeFinished()  
{  
    if(InitServer())  
    {  
        QDialog::accept();  
    }  
}  
主函数:

在主函数中添加CUsrLogin.. 和 信号槽函数。

代码语言:javascript
复制
int main(int argc, char * argv[])  
{  
    QApplication app(argc, argv);  

    QString name = "******"; // 自定义程序名称  
<span style="color:#ff0000;">   CUsrLogin login(name);  
    if(!login.InitServer())  
    {  
        int ret = login.exec();  
        if(QDialog::Accepted == ret)  
        {  
            if( login.GetIndex() == PROCESS_SHOW ||  
                login.GetIndex() == PROCESS_STOP )  
            {  
                return 1;  
            }  
        }  
        else  
        {  
            return 1;  
        }  
    }  
</span>  
    MainWindow mainWin;  
    mainWin.show();  
    return app.exec();  
}  
MainWindow中实现:
代码语言:javascript
复制
void MainWindow::slotProcAppMessage( const QString& order)  
{  
    if(order == PRO_SHOW)  
    {  
        #ifdef WIN32  
        {  
            activateWindow();  
            showMinimized();  
            showMaximized();  
        }  
        #else  
        {  
            activateWindow();  

            if(windowState () & Qt::WindowMinimized)  
            {     
                    setWindowState(windowState() & ~Qt::WindowMinimized | Qt::WindowActive);  
                    showMaximized();  
                    show();  
            }  
            else if(windowState() & Qt::WindowMaximized)  
            {     
                    setWindowState(windowState() & Qt::WindowMaximized | Qt::WindowActive);  
            }     
            else  
            {     
                    setWindowState(windowState() & Qt::WindowMaximized | Qt::WindowActive);  
            }  
        }  
        #endif  
    }  
    else if(order == PRO_RESTART)  
    {  
        close();  
    }  
    else if(order == PRO_STOP)  
    {  
        close();  
    }  
}

3. QSingleApplication类

实现原理应该和QLocalServer和QLocalSocket相同。

使用Qt中的QSharedMemory,QLocalServer和QLocalSocket实现(不过需要在你的.pro里加上QT += network)

具体说明可以参考:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Linux知识积累 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 共享内存的方法
  • 2. 使用QLocalServer和QLocalSocket类
    • 头文件:
      • 主函数:
        • MainWindow中实现:
        • 3. QSingleApplication类
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档