12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #ifndef LINUX_EVENT_H
- #define LINUX_EVENT_H
- #include <sys/epoll.h>
- #include <sys/eventfd.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <cstring>
- #include <iostream>
- #include <vector>
- #include <mutex>
- #include <unordered_map>
- #include <memory>
- #include <system_error>
- // 辅助函数:生成带时间戳的日志前缀
- inline std::string getLogPrefix() {
- auto now = std::chrono::system_clock::now();
- std::time_t time = std::chrono::system_clock::to_time_t(now);
- char timeStr[26];
- ctime_r(&time, timeStr);
- timeStr[24] = '\0'; // 移除换行符
- return "[" + std::string(timeStr) + "] [WARNING] ";
- }
- class LinuxEvent {
- public:
- enum EventType {
- AUTO_RESET,
- MANUAL_RESET
- };
- LinuxEvent(EventType type = MANUAL_RESET, bool initialState = false);
- ~LinuxEvent();
- // 禁止拷贝和赋值
- LinuxEvent(const LinuxEvent&) = delete;
- LinuxEvent& operator=(const LinuxEvent&) = delete;
-
- void SetEvent();
- void ResetEvent();
- bool IsSet() const;
- int GetFD() const;
- bool Wait(unsigned long timeoutMs = (unsigned long)-1);
- static int WaitForMultipleEvents(LinuxEvent** events, int count, unsigned long timeoutMs);
- static int WaitForMultipleEvents(std::vector<std::shared_ptr<LinuxEvent>>& events, unsigned long timeoutMs);
- // 跨进程支持
- static std::shared_ptr<LinuxEvent> OpenEvent(const char* name, bool inheritHandle = false);
- static std::shared_ptr<LinuxEvent> CreateEvent(EventType type, bool initialState, const char* name ="");
- static void CleanupNamedEvents();
- private:
- mutable std::mutex m_mutex;
- int m_fd;
- EventType m_type;
- bool m_state;
- std::string m_name; // 用于命名事件
- // 用于命名事件管理的静态成员
- static std::mutex s_namedEventsMutex;
- static std::unordered_map<std::string, std::weak_ptr<LinuxEvent>> s_namedEvents;
- };
- #endif // LINUX_EVENT_H
|