这里以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);
}