Linux Qt只能运行一个实例的完美方案

程序名称可以被改
#include <QApplication>
#include <QLocalSocket>
#include <QLocalServer>
#include <QFile>


#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
size_t get_executable_path( char* processdir,char* processname, size_t len)
{
    char* path_end;
    if(readlink("/proc/self/exe", processdir,len) <=0)
        return -1;
    path_end = strrchr(processdir,  '/');
    if(path_end == NULL)
        return -1;
    ++path_end;
    strcpy(processname, path_end );
    *path_end = '\0';
    return (size_t)(path_end - processdir);
}

bool is_running;
QLocalServer *server;
void checkSinglt()
{
    char path[200];
    char processname[50];
    memset( path, 0, 200 );
    memset( processname, 0, 50 );
    std::cout<<"@@@ @@###### Check Instance!!! #######@@ @@@"<<std::endl;
    is_running = false;
    size_t sizx = get_executable_path( path, processname, sizeof(path) );
    QCoreApplication::setApplicationName(processname);
    QString serverName = QCoreApplication::applicationName();
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if(socket.waitForConnected(500))
    {
        is_running =true;
        return;
    }

    //连接不上服务器,就创建一个
    server =new QLocalServer();
    // connect(server, SIGNAL(newConnection()), this,SLOT(newLocalConnection()));
    if(server->listen(serverName))
    {
        //防止程序崩溃时,残留进程服务,移除之
        if( server->serverError() == QAbstractSocket::AddressInUseError &&QFile::exists(server->serverName()))
        {
            QFile::remove(server->serverName());
            server->listen(serverName);
        }
    }
}

#include <QMessageBox>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    checkSinglt();
    if(is_running)
    {
        std::cout<<"@@@ Error Exist Instance"<<std::endl;
        QMessageBox::information(NULL, "Singnlt", "Error Already Has An Instance!!!", QMessageBox::Ok);
        exit(0);
    }
    return a.exec(); 
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值