98 lines
2.3 KiB
C++
98 lines
2.3 KiB
C++
#include "FileHelper.h"
|
|
#include <QDebug>
|
|
#include <QFileInfo>
|
|
#include <QThread>
|
|
|
|
namespace
|
|
{
|
|
QString processImageName(const QString& exeName)
|
|
{
|
|
QString name = QFileInfo(exeName).fileName().trimmed();
|
|
#ifndef Q_OS_WIN
|
|
if (name.endsWith(QStringLiteral(".exe"), Qt::CaseInsensitive))
|
|
name.chop(4);
|
|
#endif
|
|
return name;
|
|
}
|
|
}
|
|
|
|
bool FileHelper::createDir(const QString &path)
|
|
{
|
|
QDir dir(path);
|
|
if (!dir.exists())
|
|
return dir.mkpath(".");
|
|
return true;
|
|
}
|
|
|
|
bool FileHelper::copyFileOverwrite(const QString &src, const QString &dst)
|
|
{
|
|
if (QFile::exists(dst))
|
|
{
|
|
if (!QFile::remove(dst))
|
|
{
|
|
qDebug() << "Cannot remove old file:" << dst;
|
|
return false;
|
|
}
|
|
}
|
|
return QFile::copy(src, dst);
|
|
}
|
|
|
|
bool FileHelper::isProcessRunning(const QString &exeName)
|
|
{
|
|
const QString imageName = processImageName(exeName);
|
|
if (imageName.isEmpty())
|
|
return false;
|
|
|
|
QProcess process;
|
|
#ifdef Q_OS_WIN
|
|
process.start(QStringLiteral("tasklist"), QStringList{
|
|
QStringLiteral("/FI"),
|
|
QStringLiteral("IMAGENAME eq %1").arg(imageName)
|
|
});
|
|
process.waitForFinished();
|
|
const QString output = QString::fromLocal8Bit(process.readAllStandardOutput());
|
|
return output.contains(imageName, Qt::CaseInsensitive);
|
|
#elif defined(Q_OS_UNIX)
|
|
process.start(QStringLiteral("pgrep"), QStringList{
|
|
QStringLiteral("-x"),
|
|
imageName
|
|
});
|
|
process.waitForFinished(1000);
|
|
return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
|
|
#else
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
bool FileHelper::killProcess(const QString &exeName)
|
|
{
|
|
if (!isProcessRunning(exeName))
|
|
return true;
|
|
const QString imageName = processImageName(exeName);
|
|
if (imageName.isEmpty())
|
|
return true;
|
|
|
|
QProcess process;
|
|
#ifdef Q_OS_WIN
|
|
process.start(QStringLiteral("taskkill"), QStringList{
|
|
QStringLiteral("/f"),
|
|
QStringLiteral("/im"),
|
|
imageName
|
|
});
|
|
#elif defined(Q_OS_UNIX)
|
|
process.start(QStringLiteral("pkill"), QStringList{
|
|
QStringLiteral("-x"),
|
|
imageName
|
|
});
|
|
#else
|
|
return false;
|
|
#endif
|
|
process.waitForFinished(3000);
|
|
for (int i = 0; i < 20; ++i) {
|
|
if (!isProcessRunning(imageName))
|
|
return true;
|
|
QThread::msleep(100);
|
|
}
|
|
return false;
|
|
}
|