LinuxEvent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #include "LinuxEvent.h"
  2. #include <sys/mman.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <cstring>
  7. // 初始化静态成员
  8. std::mutex LinuxEvent::s_namedEventsMutex;
  9. std::unordered_map<std::string, std::weak_ptr<LinuxEvent>> LinuxEvent::s_namedEvents;
  10. LinuxEvent::LinuxEvent(EventType type, bool initialState)
  11. : m_type(type), m_state(initialState) {
  12. m_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
  13. if (m_fd == -1) {
  14. throw std::system_error(errno, std::system_category(), "eventfd creation failed");
  15. }
  16. if (initialState) {
  17. SetEvent();
  18. }
  19. }
  20. LinuxEvent::~LinuxEvent() {
  21. if (m_fd != -1) {
  22. close(m_fd);
  23. m_fd = -1;
  24. }
  25. // 从命名事件映射中移除(仅当有名称时)
  26. if (!m_name.empty()) {
  27. std::lock_guard<std::mutex> lock(s_namedEventsMutex);
  28. s_namedEvents.erase(m_name);
  29. }
  30. }
  31. void LinuxEvent::SetEvent() {
  32. if (this == nullptr) { // 关键空指针检查
  33. std::cerr << getLogPrefix() << "LinuxEvent::SetEvent called with NULL pointer! Possible invalid object or early destruction." << std::endl;
  34. return; // 避免继续执行导致崩溃
  35. }
  36. std::lock_guard<std::mutex> lock(m_mutex);
  37. std::cout << getLogPrefix() << "SetEvent: Lock acquired. Current state: " << m_state << std::endl;
  38. const uint64_t value = 1;
  39. ssize_t result = write(m_fd, &value, sizeof(value));
  40. if (result == -1) {
  41. if (errno == EAGAIN) {
  42. std::cout << getLogPrefix() << "SetEvent: Write would block (EAGAIN). Eventfd counter full?" << std::endl;
  43. }
  44. else {
  45. std::cerr << getLogPrefix() << "SetEvent: WRITE FAILED! errno=" << errno
  46. << " (" << strerror(errno) << ")" << std::endl;
  47. throw std::system_error(errno, std::system_category(), "eventfd write failed");
  48. }
  49. }
  50. else if (result != sizeof(value)) {
  51. std::cerr << getLogPrefix() << "SetEvent: PARTIAL WRITE! " << result << "/" << sizeof(value)
  52. << " bytes written" << std::endl;
  53. }
  54. else {
  55. std::cout << getLogPrefix() << "SetEvent: Successfully wrote event value=" << value << std::endl;
  56. }
  57. m_state = true;
  58. std::cout << getLogPrefix() << "SetEvent: State set to TRUE" << std::endl;
  59. }
  60. void LinuxEvent::ResetEvent() {
  61. std::lock_guard<std::mutex> lock(m_mutex);
  62. uint64_t value;
  63. ssize_t bytesRead;
  64. // 清空所有事件计数
  65. while (true) {
  66. bytesRead = read(m_fd, &value, sizeof(value));
  67. if (bytesRead == sizeof(value)) {
  68. // 成功读取一个事件值
  69. std::cout << "ResetEvent: consumed event value = " << value << std::endl;
  70. }
  71. else if (bytesRead == -1 && errno == EAGAIN) {
  72. // 没有更多数据可读
  73. std::cout << "ResetEvent: eventfd drained" << std::endl;
  74. break;
  75. }
  76. else if (bytesRead == -1) {
  77. // 其他错误
  78. std::cerr << "ResetEvent: read error, errno = " << errno << " (" << strerror(errno) << ")" << std::endl;
  79. break;
  80. }
  81. else {
  82. // 读取字节数异常(不应该发生)
  83. std::cerr << "ResetEvent: unexpected read size: " << bytesRead << std::endl;
  84. break;
  85. }
  86. }
  87. m_state = false;
  88. std::cout << "ResetEvent: state reset to false" << std::endl;
  89. }
  90. bool LinuxEvent::IsSet() const {
  91. std::lock_guard<std::mutex> lock(m_mutex);
  92. return m_state;
  93. }
  94. int LinuxEvent::GetFD() const {
  95. return m_fd;
  96. }
  97. bool LinuxEvent::Wait(unsigned long timeoutMs) {
  98. std::cout << getLogPrefix() << "Wait: Entering. Timeout: "
  99. << (timeoutMs == static_cast<unsigned long>(-1) ? "INFINITE" : std::to_string(timeoutMs) + "ms")
  100. << ", Current state: " << m_state << std::endl;
  101. int epollFd = epoll_create1(0);
  102. if (epollFd == -1) {
  103. std::cerr << getLogPrefix() << "Wait: epoll_create1 FAILED! errno="
  104. << errno << " (" << strerror(errno) << ")" << std::endl;
  105. throw std::system_error(errno, std::system_category(), "epoll_create1 failed");
  106. }
  107. std::cout << getLogPrefix() << "Wait: epoll instance created (fd=" << epollFd << ")" << std::endl;
  108. struct epoll_event ev;
  109. ev.events = EPOLLIN;
  110. ev.data.fd = m_fd;
  111. if (epoll_ctl(epollFd, EPOLL_CTL_ADD, m_fd, &ev) == -1) {
  112. std::cerr << getLogPrefix() << "Wait: epoll_ctl(ADD) FAILED! fd=" << m_fd
  113. << ", errno=" << errno << " (" << strerror(errno) << ")" << std::endl;
  114. close(epollFd);
  115. throw std::system_error(errno, std::system_category(), "epoll_ctl failed");
  116. }
  117. std::cout << getLogPrefix() << "Wait: Added eventfd (fd=" << m_fd
  118. << ") to epoll instance" << std::endl;
  119. int ready = 0;
  120. struct epoll_event events[1];
  121. int timeout = (timeoutMs == static_cast<unsigned long>(-1)) ? -1 : static_cast<int>(timeoutMs);
  122. std::cout << getLogPrefix() << "Wait: Blocking on epoll_wait (timeout=" << timeout << "ms)..." << std::endl;
  123. ready = epoll_wait(epollFd, events, 1, timeout);
  124. if (ready == -1) {
  125. std::cerr << getLogPrefix() << "Wait: epoll_wait FAILED! errno="
  126. << errno << " (" << strerror(errno) << ")" << std::endl;
  127. }
  128. close(epollFd);
  129. std::cout << getLogPrefix() << "Wait: Closed epoll instance" << std::endl;
  130. if (ready > 0) {
  131. std::cout << getLogPrefix() << "Wait: EVENT SIGNALED! Ready FDs: " << ready << std::endl;
  132. if (m_type == AUTO_RESET) {
  133. uint64_t value;
  134. if (read(m_fd, &value, sizeof(value)) == -1 && errno != EAGAIN) {
  135. throw std::system_error(errno, std::system_category(), "eventfd read failed in Wait");
  136. }
  137. m_state = false;
  138. }
  139. return true;
  140. }
  141. else if (ready == 0) {
  142. std::cout << getLogPrefix() << "Wait: TIMEOUT reached" << std::endl;
  143. }
  144. else {
  145. std::cerr << getLogPrefix() << "Wait: UNEXPECTED epoll_wait result: " << ready << std::endl;
  146. }
  147. return false;
  148. }
  149. int LinuxEvent::WaitForMultipleEvents(LinuxEvent** events, int count, unsigned long timeoutMs) {
  150. if (count <= 0) return -1;
  151. int epollFd = epoll_create1(0);
  152. if (epollFd == -1) {
  153. throw std::system_error(errno, std::system_category(), "epoll_create1 failed");
  154. }
  155. // 添加所有事件到epoll
  156. for (int i = 0; i < count; i++) {
  157. struct epoll_event ev;
  158. ev.events = EPOLLIN;
  159. ev.data.u32 = i; // 存储事件索引
  160. if (epoll_ctl(epollFd, EPOLL_CTL_ADD, events[i]->GetFD(), &ev) == -1) {
  161. close(epollFd);
  162. throw std::system_error(errno, std::system_category(), "epoll_ctl add failed");
  163. }
  164. }
  165. // 等待事件
  166. int maxEvents = std::min(count, 1024);
  167. std::vector<struct epoll_event> epollEvents(maxEvents);
  168. int timeout = (timeoutMs == static_cast<unsigned long>(-1)) ? -1 : static_cast<int>(timeoutMs);
  169. int ready = epoll_wait(epollFd, epollEvents.data(), maxEvents, timeout);
  170. int result = -1;
  171. if (ready > 0) {
  172. // 找到索引最小的事件
  173. int minIndex = count;
  174. for (int i = 0; i < ready; i++) {
  175. if (static_cast<int>(epollEvents[i].data.u32) < minIndex) {
  176. minIndex = epollEvents[i].data.u32;
  177. }
  178. }
  179. result = minIndex;
  180. }
  181. // 清理
  182. for (int i = 0; i < count; i++) {
  183. epoll_ctl(epollFd, EPOLL_CTL_DEL, events[i]->GetFD(), nullptr);
  184. }
  185. close(epollFd);
  186. return result;
  187. }
  188. int LinuxEvent::WaitForMultipleEvents(std::vector<std::shared_ptr<LinuxEvent>>& events, unsigned long timeoutMs) {
  189. int count = events.size();
  190. if (count <= 0) return -1;
  191. int epollFd = epoll_create1(0);
  192. if (epollFd == -1) {
  193. throw std::system_error(errno, std::system_category(), "epoll_create1失败");
  194. }
  195. // 添加所有事件到epoll
  196. for (int i = 0; i < count; i++) {
  197. struct epoll_event ev;
  198. ev.events = EPOLLIN;
  199. ev.data.u32 = i; // 存储事件索引
  200. if (epoll_ctl(epollFd, EPOLL_CTL_ADD, events[i]->GetFD(), &ev) == -1) {
  201. close(epollFd);
  202. throw std::system_error(errno, std::system_category(), "epoll_ctl添加失败");
  203. }
  204. }
  205. // 等待事件
  206. int maxEvents = std::min(count, 1024);
  207. std::vector<struct epoll_event> epollEvents(maxEvents);
  208. int timeout = (timeoutMs == static_cast<unsigned long>(-1)) ? -1 : static_cast<int>(timeoutMs);
  209. int ready = epoll_wait(epollFd, epollEvents.data(), maxEvents, timeout);
  210. int result = -1;
  211. if (ready > 0) {
  212. // 找到索引最小的事件
  213. int minIndex = count;
  214. for (int i = 0; i < ready; i++) {
  215. if (static_cast<int>(epollEvents[i].data.u32) < minIndex) {
  216. minIndex = epollEvents[i].data.u32;
  217. }
  218. }
  219. result = minIndex;
  220. }
  221. // 清理
  222. for (int i = 0; i < count; i++) {
  223. epoll_ctl(epollFd, EPOLL_CTL_DEL, events[i]->GetFD(), nullptr);
  224. }
  225. close(epollFd);
  226. return result;
  227. }
  228. std::shared_ptr<LinuxEvent> LinuxEvent::CreateEvent(EventType type, bool initialState, const char* name) {
  229. // 如果未提供名称或名称为空字符串,创建未命名事件
  230. if (name == nullptr || *name == '\0') {
  231. return std::make_shared<LinuxEvent>(type, initialState);
  232. }
  233. std::string eventName(name);
  234. std::lock_guard<std::mutex> lock(s_namedEventsMutex);
  235. // 检查是否已存在同名事件
  236. auto it = s_namedEvents.find(eventName);
  237. if (it != s_namedEvents.end()) {
  238. if (auto existing = it->second.lock()) {
  239. return existing;
  240. }
  241. }
  242. // 创建新命名事件
  243. auto newEvent = std::make_shared<LinuxEvent>(type, initialState);
  244. newEvent->m_name = eventName;
  245. s_namedEvents[eventName] = newEvent;
  246. return newEvent;
  247. }
  248. std::shared_ptr<LinuxEvent> LinuxEvent::OpenEvent(const char* name, bool inheritHandle) {
  249. if (name == nullptr || *name == '\0') {
  250. throw std::invalid_argument("Invalid event name");
  251. }
  252. CleanupNamedEvents();
  253. std::string eventName(name);
  254. std::lock_guard<std::mutex> lock(s_namedEventsMutex);
  255. auto it = s_namedEvents.find(eventName);
  256. if (it == s_namedEvents.end()) {
  257. return nullptr; // 未找到
  258. }
  259. if (auto event = it->second.lock()) {
  260. return event;
  261. }
  262. // 弱引用已过期,从映射中移除
  263. s_namedEvents.erase(it);
  264. return nullptr;
  265. }
  266. void LinuxEvent::CleanupNamedEvents() {
  267. std::lock_guard<std::mutex> lock(s_namedEventsMutex);
  268. for (auto it = s_namedEvents.begin(); it != s_namedEvents.end(); ) {
  269. if (it->second.expired()) {
  270. it = s_namedEvents.erase(it);
  271. } else {
  272. ++it;
  273. }
  274. }
  275. }