How to check if a program is running by its name with Qt (C++)

前端 未结 3 1908
情深已故
情深已故 2021-02-04 13:37

How to check if a program is running, by its name, with Qt (C++).

Will QProcess::pid do the job? I don\'t know how to use it. Please suggest.

3条回答
  •  粉色の甜心
    2021-02-04 14:05

    A quick and dirty way to do it would be to just check the output of tasklist, something like:

    bool isRunning(const QString &process) {
      QProcess tasklist;
      tasklist.start(
            "tasklist",
            QStringList() << "/NH" 
                          << "/FO" << "CSV" 
                          << "/FI" << QString("IMAGENAME eq %1").arg(process));
      tasklist.waitForFinished();
      QString output = tasklist.readAllStandardOutput();
      return output.startsWith(QString("\"%1").arg(process));
    }
    

    Using EnumProcesses is probably a better way (i.e. more "pure"; certainly more performant), but this may be "good enough" as long as this isn't being called in a big loop or something. The same idea could also be ported to other platforms as well, although obviously the command tool and parsing logic would be different.

提交回复
热议问题