Qt笔记-进程只能存在1个(Linux适用,Windows有思路)

388 篇文章 20 订阅
140 篇文章 11 订阅

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

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

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

这里创建了一个类

QApplicationRun.h

#ifndef QAPPLICATIONRUN_H
#define QAPPLICATIONRUN_H

#include <QObject>

class QApplicationRun : public QObject
{
    Q_OBJECT
public:
    QApplicationRun(QObject *parent = 0);

    static bool isProgramAlreadyRunningInOS();
};

#endif // QAPPLICATIONRUNONECE_H

QApplicationRun.cpp

#include "QApplicationRun.h"
#include <QCoreApplication>
#include <QDebug>
#include <QProcess>

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT1995

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

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

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

打赏作者

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

抵扣说明:

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

余额充值