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();