#include #include #include "CCThread.h" #include #include "CCSystem.h" #include "CCApplication.h" #include "CCProcess.h" #include "CCSocket.h" #ifdef _WIN32 #include #include #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 } static bool Flag = true; inline CTL::Socket socket_t; bool CloseConnect() { Flag = false; CTL::System::Println("CloseConnect"); return false; } void CloseApp(const CTL::String& exe){ #ifdef _WIN32 const auto str = CTL::String::format("taskkill -f -t -im {}",exe.c_str()); #elif __linux__ const auto str = CTL::String::format("killall -9 {}",exe.c_str()); #endif CTL::System::Execute(str); } 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; CTL::Application app(argc, argv); CC::SetCloseFun(CloseConnect); const CTL::String Bit = argv[1]; if(Bit != "TCP_Daemon"){ while (Flag){ bool F = IsProcessRunning(argv[2]); // CTL::System::Println("IsProcessRunning %d",F ? 1 : 0); if(!F){ CTL::Process app_t; CloseApp(argv[2]); app_t.AddCommand(argv[3]); app_t.Start(); } CTL::Thread::SleepMS(5 * 1000); } CloseApp(argv[2]); } else{ socket_t.Init(CTL::IPV4,CTL::TCP); while (Flag){ const int Port = CTL::String(argv[2]).to_int(); const bool F = socket_t.Connect("127.0.0.1",Port); if(F){ char buffer[1024]{}; const auto len = socket_t.RecvData(buffer,sizeof buffer); socket_t.Close(); socket_t.Init(CTL::IPV4,CTL::TCP); CTL::System::Println("TCP_Daemon Close {}",argv[3]); } else{ CTL::Process app_t; CloseApp(argv[4]); app_t.AddCommand(argv[3]); app_t.Start(); CTL::System::Println("Auto Start {}",argv[3]); } CTL::Thread::SleepMS(5 * 1000); } } return 0; }