89 lines
2.3 KiB
C++
89 lines
2.3 KiB
C++
#include <QCoreApplication>
|
|
#include <QString>
|
|
#include <QFuture>
|
|
#include <windows.h>
|
|
#include <tlhelp32.h>
|
|
#include <iostream>
|
|
#include "CCThread.h"
|
|
#include "QProcess"
|
|
#include "QSharedMemory"
|
|
|
|
|
|
bool IsProcessRunning(const std::string& processName) {
|
|
#ifdef _WIN32
|
|
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
|
if (hSnapshot == INVALID_HANDLE_VALUE) {
|
|
return false;
|
|
}
|
|
|
|
PROCESSENTRY32 pe;
|
|
pe.dwSize = sizeof(PROCESSENTRY32);
|
|
|
|
if (!Process32First(hSnapshot, &pe)) {
|
|
CloseHandle(hSnapshot);
|
|
return false;
|
|
}
|
|
|
|
do {
|
|
if (processName == pe.szExeFile) {
|
|
CloseHandle(hSnapshot);
|
|
return true;
|
|
}
|
|
} while (Process32Next(hSnapshot, &pe));
|
|
|
|
CloseHandle(hSnapshot);
|
|
return false;
|
|
#elif __linux__
|
|
DIR* dir = opendir("/proc");
|
|
if (!dir) {
|
|
return false;
|
|
}
|
|
|
|
struct dirent* entry;
|
|
while ((entry = readdir(dir)) != nullptr) {
|
|
if (entry->d_type == DT_DIR) {
|
|
// Check if the directory name is a number
|
|
if (entry->d_name[0] >= '0' && entry->d_name[0] <= '9') {
|
|
std::string pid = entry->d_name;
|
|
std::ifstream commFile("/proc/" + pid + "/comm");
|
|
if (commFile.is_open()) {
|
|
std::string comm;
|
|
std::getline(commFile, comm);
|
|
comm.pop_back(); // Remove newline character
|
|
if (comm == processName) {
|
|
closedir(dir);
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
closedir(dir);
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if(argc < 3){
|
|
return -2;
|
|
}
|
|
std::cout << argv[0] << std::endl;
|
|
std::cout << argv[1] << std::endl;
|
|
std::cout << argv[2] << std::endl;
|
|
std::cout << argv[3] << std::endl;
|
|
static auto *shareMem = new QSharedMemory(argv[1]); //创建“SingleApp”的共享内存块
|
|
if (!shareMem->create(1)){ //创建大小1b的内存
|
|
return -1;
|
|
}
|
|
QCoreApplication a(argc, argv);
|
|
while (true){
|
|
bool F = IsProcessRunning(argv[2]);
|
|
if(!F){
|
|
QProcess::startDetached(argv[3]);
|
|
}
|
|
Threading::Sleep(1000 * 1000 * 5);
|
|
}
|
|
return QCoreApplication::exec();
|
|
}
|