如何使用Qt(C++)检查程序是否正在运行,以其名称为标识。
QProcess::pid
是否能够胜任这项工作?我不知道如何使用它。请建议。
如何使用Qt(C++)检查程序是否正在运行,以其名称为标识。
QProcess::pid
是否能够胜任这项工作?我不知道如何使用它。请建议。
EnumProcesses
函数实现您想要的功能的方法,Microsoft网站提供了如何使用它的完整示例。
http://msdn.microsoft.com/en-us/library/ms682623.aspx
为了获取,您需要使用以下函数替换PrintProcessNameAndID:
bool matchProcessName( DWORD processID, std::string processName)
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Compare process name with your string
bool matchFound = !_tcscmp(szProcessName, processName.c_str() );
// Release the handle to the process.
CloseHandle( hProcess );
return matchFound;
}
快速并且简单的方法是只需要检查tasklist
的输出,就像这样:
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));
}
使用EnumProcesses
可能是更好的方式(即更“纯粹”;当然更高效),但只要不在大循环或类似情况下调用,这种方法就足够好了。相同的思路也可以移植到其他平台上,尽管命令工具和解析逻辑显然会有所不同。
//How to Run App
bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() << "Run = " << ok;
//How to Kill App
system("taskkill /im CozxyLogger.exe /f");
qDebug() << "Close";
QProcess
对象,然后在其上调用它。 - chris