Service_NSSM/main.cpp

116 lines
3.0 KiB
C++
Raw Normal View History

2025-09-27 14:24:18 +08:00
#include <dirent.h>
#include <iostream>
#include "CCThread.h"
#include <fstream>
#include "CCSystem.h"
2025-09-30 16:24:15 +08:00
#include "CCApplication.h"
#include "CCProcess.h"
2025-09-27 14:24:18 +08:00
#ifdef _WIN32
#include <windows.h>
#include <tlhelp32.h>
#endif
bool IsProcessRunning(const std::string& processName) {
#ifdef _WIN32
// Windows 实现
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 (_stricmp(pe.szExeFile, processName.c_str()) == 0) {
CloseHandle(hSnapshot);
return true;
}
} while (Process32Next(hSnapshot, &pe));
CloseHandle(hSnapshot);
return false;
#elif __linux__
// Linux 实现
DIR* dir = opendir("/proc");
if (!dir) {
return false;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_DIR) {
std::string pid = entry->d_name;
// 检查是否为数字目录
if (!pid.empty() && std::all_of(pid.begin(), pid.end(), ::isdigit)) {
std::string commPath = "/proc/" + pid + "/comm";
std::ifstream commFile(commPath);
if (commFile.is_open()) {
std::string comm;
std::getline(commFile, comm);
// 移除换行符(如果有)
if (!comm.empty() && comm.back() == '\n') {
comm.pop_back();
}
// 比较进程名(不区分大小写)
if (strcasecmp(comm.c_str(), processName.c_str()) == 0) {
closedir(dir);
return true;
}
}
}
}
}
closedir(dir);
return false;
#else
#error "Unsupported platform"
#endif
}
2025-09-30 16:24:15 +08:00
inline bool Flag = true;
2025-09-27 14:24:18 +08:00
bool CloseConnect() {
Flag = false;
CTL::System::Println("CloseConnect");
// CTL::System::Exit();
return false;
}
int main(int argc, char *argv[]) {
if(argc < 3){
return -2;
}
2025-09-30 16:24:15 +08:00
if(!CTL::Application::IsSingleInstance()){
2025-09-27 14:24:18 +08:00
return -1;
}
2025-09-30 16:24:15 +08:00
CTL::Application app(argc, argv);
// std::cout << argv[0] << std::endl;
// std::cout << argv[1] << std::endl; // 守护服务进程名称
// std::cout << argv[2] << std::endl; // 进程名称
// std::cout << argv[3] << std::endl; // 启动路径
CTL::System::Println("Start Daemon {}",argv[2]);
2025-09-27 14:24:18 +08:00
CC::SetCloseFun(CloseConnect);
while (Flag){
bool F = IsProcessRunning(argv[2]);
// CTL::System::Println("IsProcessRunning %d",F ? 1 : 0);
if(!F){
2025-09-30 16:24:15 +08:00
CTL::Process process;
process.Command(argv[2]);
process.Start();
process.Stop();
2025-09-27 14:24:18 +08:00
}
2025-09-30 16:24:15 +08:00
CTL::Thread::SleepMS(5 * 1000);
2025-09-27 14:24:18 +08:00
}
2025-09-30 16:24:15 +08:00
return CTL::Application::Running(&app);
2025-09-27 14:24:18 +08:00
}