LinuxEvent.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef LINUX_EVENT_H
  2. #define LINUX_EVENT_H
  3. #include <sys/epoll.h>
  4. #include <sys/eventfd.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <errno.h>
  8. #include <cstring>
  9. #include <iostream>
  10. #include <vector>
  11. #include <mutex>
  12. #include <unordered_map>
  13. #include <memory>
  14. #include <system_error>
  15. // 辅助函数:生成带时间戳的日志前缀
  16. inline std::string getLogPrefix() {
  17. auto now = std::chrono::system_clock::now();
  18. std::time_t time = std::chrono::system_clock::to_time_t(now);
  19. char timeStr[26];
  20. ctime_r(&time, timeStr);
  21. timeStr[24] = '\0'; // 移除换行符
  22. return "[" + std::string(timeStr) + "] [WARNING] ";
  23. }
  24. class LinuxEvent {
  25. public:
  26. enum EventType {
  27. AUTO_RESET,
  28. MANUAL_RESET
  29. };
  30. LinuxEvent(EventType type = MANUAL_RESET, bool initialState = false);
  31. ~LinuxEvent();
  32. // 禁止拷贝和赋值
  33. LinuxEvent(const LinuxEvent&) = delete;
  34. LinuxEvent& operator=(const LinuxEvent&) = delete;
  35. void SetEvent();
  36. void ResetEvent();
  37. bool IsSet() const;
  38. int GetFD() const;
  39. bool Wait(unsigned long timeoutMs = (unsigned long)-1);
  40. static int WaitForMultipleEvents(LinuxEvent** events, int count, unsigned long timeoutMs);
  41. static int WaitForMultipleEvents(std::vector<std::shared_ptr<LinuxEvent>>& events, unsigned long timeoutMs);
  42. // 跨进程支持
  43. static std::shared_ptr<LinuxEvent> OpenEvent(const char* name, bool inheritHandle = false);
  44. static std::shared_ptr<LinuxEvent> CreateEvent(EventType type, bool initialState, const char* name ="");
  45. static void CleanupNamedEvents();
  46. private:
  47. mutable std::mutex m_mutex;
  48. int m_fd;
  49. EventType m_type;
  50. bool m_state;
  51. std::string m_name; // 用于命名事件
  52. // 用于命名事件管理的静态成员
  53. static std::mutex s_namedEventsMutex;
  54. static std::unordered_map<std::string, std::weak_ptr<LinuxEvent>> s_namedEvents;
  55. };
  56. #endif // LINUX_EVENT_H