前言
这里提供两种可以判断Linux下某程序是否正在运行的方法,两种都是通过执行终端命令,获取结果并判断来实现的
方法1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| int checkProgramRun(const QString & ProcessName) { QString LinuxProcessName = ProcessName;
QProcess process; process.setReadChannel(QProcess::StandardOutput);
process.start("ps -ef"); process.waitForFinished();
QByteArray bytes = process.readAll(); process.close();
char* ch; QByteArray ba = LinuxProcessName.toLatin1(); ch = ba.data(); if(bytes.contains(ch)) { return 1; }
return 0; }
|
方法2
注:这里用到了grep,如果直接用QProcess的start方法执行命令是获取不到grep筛选后的结果的,暂不知原因,这里采用执行shell和echo打印相结合的方法可以成功打印出结果,但还是有小问题,结果是两行,这里只能出现一行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| int checkProgramRun(const QString & ProcessName) { QString LinuxProcessName = ProcessName;
QProcess process; QStringList args; args<<"-c"; QString strCommnd = QString("echo $(ps -ef | grep %1 | grep -v grep)").arg(LinuxProcessName); args<<strCommnd;
process.start("sh",args); process.waitForFinished();
QString programs = process.readAllStandardOutput(); process.close();
if(programs.contains(LinuxProcessName)) { return 1; }
return 0; }
|