Service_NSSM/main.cpp

89 lines
2.3 KiB
C++
Raw Normal View History

2025-03-06 13:47:33 +08:00
#include <QCoreApplication>
#include <QString>
#include <QFuture>
#include <windows.h>
#include <tlhelp32.h>
2025-07-19 09:43:46 +08:00
#include <iostream>
2025-03-06 13:47:33 +08:00
#include "CCThread.h"
#include "QProcess"
2025-07-19 09:43:46 +08:00
#include "QSharedMemory"
2025-03-06 13:47:33 +08:00
2025-07-19 09:43:46 +08:00
bool IsProcessRunning(const std::string& processName) {
#ifdef _WIN32
2025-03-06 13:47:33 +08:00
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
2025-07-19 09:43:46 +08:00
if (hSnapshot == INVALID_HANDLE_VALUE) {
2025-03-06 13:47:33 +08:00
return false;
2025-07-19 09:43:46 +08:00
}
2025-03-06 13:47:33 +08:00
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32);
2025-07-19 09:43:46 +08:00
if (!Process32First(hSnapshot, &pe)) {
CloseHandle(hSnapshot);
return false;
2025-03-06 13:47:33 +08:00
}
2025-07-19 09:43:46 +08:00
do {
if (processName == pe.szExeFile) {
CloseHandle(hSnapshot);
return true;
}
} while (Process32Next(hSnapshot, &pe));
2025-03-06 13:47:33 +08:00
CloseHandle(hSnapshot);
2025-07-19 09:43:46 +08:00
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
2025-03-06 13:47:33 +08:00
}
int main(int argc, char *argv[]) {
2025-07-19 09:43:46 +08:00
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的内存
2025-03-06 13:47:33 +08:00
return -1;
}
QCoreApplication a(argc, argv);
while (true){
2025-07-19 09:43:46 +08:00
bool F = IsProcessRunning(argv[2]);
2025-03-06 13:47:33 +08:00
if(!F){
2025-07-19 09:43:46 +08:00
QProcess::startDetached(argv[3]);
2025-03-06 13:47:33 +08:00
}
Threading::Sleep(1000 * 1000 * 5);
}
return QCoreApplication::exec();
}