几行代码实现c++/qt程序进程单例(文件锁)

17 篇文章 2 订阅
10 篇文章 0 订阅

qt程序进程单例(文件锁的方法)

原理

通过锁定文件,直至程序退出解锁,那么当程序第二次打开的时候检测到文件是锁定的,则退出

使用qt文件锁的方法

请在main函数里面使用,不要单独封装函数,保证锁没有退出,因为函数退出,锁也会跟着退出

#include <QLockFile>
#include <QApplication>

//文件名称(随便写)
#define INSTANCE_LOCK "singleApplication"
int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    const QString lock = QDir::homePath() + "/" + INSTANCE_LOCK;
    QLockFile lockApp(lock);

    //尝试解锁
    if (!lockApp.tryLock(200))
    {
        qDebug() << "程序已经启动,选择直接退出";
        return 0;
    }
    //程序未启动,继续进行
    return a.exec();

linux下文件锁定

#include <QApplication>
#include <QDir>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>

# define testApplicaiton "/.cache/testsingle/"
bool checkOnly()
{
    //single
    QString userName = QDir::homePath().section("/", -1, -1);
    std::string path = (QDir::homePath() + testApplicaiton).toStdString();
    QDir tdir(path.c_str());
    if (!tdir.exists()) {
        bool ret =  tdir.mkpath(path.c_str());
        qDebug() << ret ;
    }

    path += "single";
    int fd = open(path.c_str(), O_WRONLY | O_CREAT, 0644);
    int flock = lockf(fd, F_TLOCK, 0);

    if (fd == -1) {
        perror("open lockfile/n");
        return false;
    }
    if (flock == -1) {
        perror("lock file error/n");
        return false;
    }
    return true;
}

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);
    //尝试解锁
    if (!checkOnly())
    {
        qDebug() << "程序已经启动,选择直接退出";
        return 0;
    }
    //程序未启动,继续进行
    return a.exec();
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏有凉风,冬有雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值