iocp.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "iowatcher.h"
  2. #ifdef EVENT_IOCP
  3. #include "hplatform.h"
  4. #include "hdef.h"
  5. typedef struct iocp_ctx_s {
  6. HANDLE iocp;
  7. } iocp_ctx_t;
  8. int iowatcher_init(hloop_t* loop) {
  9. if (loop->iowatcher) return 0;
  10. iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)malloc(sizeof(iocp_ctx_t));
  11. iocp_ctx->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
  12. loop->iowatcher = iocp_ctx;
  13. return 0;
  14. }
  15. int iowatcher_cleanup(hloop_t* loop) {
  16. if (loop->iowatcher == NULL) return 0;
  17. iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher;
  18. CloseHandle(iocp_ctx->iocp);
  19. SAFE_FREE(loop->iowatcher);
  20. return 0;
  21. }
  22. int iowatcher_add_event(hloop_t* loop, int fd, int events) {
  23. if (loop->iowatcher == NULL) {
  24. iowatcher_init(loop);
  25. }
  26. iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher;
  27. HANDLE h = CreateIoCompletionPort((HANDLE)fd, iocp_ctx->iocp, (ULONG_PTR)events, 0);
  28. return 0;
  29. }
  30. int iowatcher_del_event(hloop_t* loop, int fd, int events) {
  31. return 0;
  32. }
  33. int iowatcher_poll_events(hloop_t* loop, int timeout) {
  34. if (loop->iowatcher == NULL) return 0;
  35. iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher;
  36. DWORD bytes = 0;
  37. ULONG_PTR key = 0;
  38. LPOVERLAPPED povlp = NULL;
  39. timeout = 3000;
  40. BOOL bRet = GetQueuedCompletionStatus(iocp_ctx->iocp, &bytes, &key, &povlp, timeout);
  41. int err = 0;
  42. if (bRet == 0) {
  43. err = GetLastError();
  44. }
  45. if (err) {
  46. if (err == ERROR_NETNAME_DELETED ||
  47. err == ERROR_OPERATION_ABORTED) {
  48. return 0;
  49. }
  50. if (povlp == NULL) {
  51. if (err == WAIT_TIMEOUT) return 0;
  52. return -1;
  53. }
  54. }
  55. if (povlp == NULL) {
  56. return -1;
  57. }
  58. if (key == NULL) {
  59. return -1;
  60. }
  61. ULONG_PTR revents = key;
  62. return 1;
  63. }
  64. #endif