Qt笔记-进程只能存在1个(Linux适用,Windows有思路)
生活随笔
收集整理的這篇文章主要介紹了
Qt笔记-进程只能存在1个(Linux适用,Windows有思路)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里以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_HQApplicationRun.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);}?
總結
以上是生活随笔為你收集整理的Qt笔记-进程只能存在1个(Linux适用,Windows有思路)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript笔记-使用反引号格式
- 下一篇: Qt工作笔记-自定义打印及存日志及std