116 lines
3.0 KiB
C++
116 lines
3.0 KiB
C++
#include <dirent.h>
|
|
#include <iostream>
|
|
#include "CCThread.h"
|
|
#include <fstream>
|
|
#include "CCSystem.h"
|
|
#include "CCApplication.h"
|
|
#include "CCProcess.h"
|
|
|
|
#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
|
|
}
|
|
|
|
inline bool Flag = true;
|
|
|
|
bool CloseConnect() {
|
|
Flag = false;
|
|
CTL::System::Println("CloseConnect");
|
|
// CTL::System::Exit();
|
|
return false;
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if(argc < 3){
|
|
return -2;
|
|
}
|
|
if(!CTL::Application::IsSingleInstance()){
|
|
return -1;
|
|
}
|
|
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]);
|
|
CC::SetCloseFun(CloseConnect);
|
|
while (Flag){
|
|
bool F = IsProcessRunning(argv[2]);
|
|
// CTL::System::Println("IsProcessRunning %d",F ? 1 : 0);
|
|
if(!F){
|
|
CTL::Process process;
|
|
process.Command(argv[2]);
|
|
process.Start();
|
|
process.Stop();
|
|
}
|
|
CTL::Thread::SleepMS(5 * 1000);
|
|
}
|
|
return CTL::Application::Running(&app);
|
|
}
|