Qt笔记-进程只能存在1个(Linux适用,Windows有思路)
发布日期:2021-06-30 10:46:43 浏览次数:2 分类:技术文章

本文共 1700 字,大约阅读时间需要 5 分钟。

这里以Linux为例主要是程序启动时,使用

ps -ef | awk '{print $2,$8,$9,$10,$11}'

这个查询下。如果是Windows可以使用tasklist去查。

这里创建了一个类

QApplicationRun.h

#ifndef QAPPLICATIONRUN_H#define QAPPLICATIONRUN_H#include 
class QApplicationRun : public QObject{ Q_OBJECTpublic: QApplicationRun(QObject *parent = 0); static bool isProgramAlreadyRunningInOS();};#endif // QAPPLICATIONRUNONECE_H

QApplicationRun.cpp

#include "QApplicationRun.h"#include 
#include
#include
QApplicationRunOnce::QApplicationRunOnce(QObject *parent) : QObject(parent){}bool QApplicationRunOnce::isProgramAlreadyRunningInOS(){ QString processName = qApp->applicationName(); int account = 0; QString cmd = "ps -ef | awk '{print $2,$8,$9,$10,$11}'"; QProcess p; p.start("bash", QStringList() << "-c" << cmd); if(!p.waitForFinished()){ qDebug() << cmd << " run failed in QApplicationRunOnece::isProgramAlreadyRunningInOS()"; return true; } QString ret = p.readAllStandardOutput(); QStringList lineList = ret.split("\n"); for(int i = 1; i < lineList.size(); i++){ QString PIDStr = lineList[i].split(" ")[0]; QString programStr = lineList[i].split(PIDStr)[1].trimmed(); QString programTmpPathNotPara = programStr.split(" ")[0]; QStringList processTmpList = programTmpPathNotPara.split("/"); QString programTmpName = processTmpList[processTmpList.size() - 1]; if(programTmpName == processName){ account++; } if(account >= 2){ return true; } } return false;}
 

调用,可以直接放到main函数里面:

if(QApplicationRun::isProgramAlreadyRunningInOS()){        qDebug() << "程序已在运行";        exit(0);    }

 

转载地址:https://it1995.blog.csdn.net/article/details/114298738 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spring Boot文档阅读笔记-DataSource configuration
下一篇:Linux工作笔记-根据PID查询进程是否存在(进程管理相关程序中常用)

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月19日 08时21分46秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章