关键词搜索

源码搜索 ×
×

漫话Redis源码之八十一

发布2022-02-13浏览456次

详情内容

fd_set是网络编程中很重要的结构体,rfds是读描述集, wfds是写描述集合,这是使用需要非常清晰,看最后的select, 知道怎么样了吧:

  1. #include <sys/select.h>
  2. #include <string.h>
  3. typedef struct aeApiState {
  4. fd_set rfds, wfds;
  5. /* We need to have a copy of the fd sets as it's not safe to reuse
  6. * FD sets after select(). */
  7. fd_set _rfds, _wfds;
  8. } aeApiState;
  9. static int aeApiCreate(aeEventLoop *eventLoop) {
  10. aeApiState *state = zmalloc(sizeof(aeApiState));
  11. if (!state) return -1;
  12. FD_ZERO(&state->rfds);
  13. FD_ZERO(&state->wfds);
  14. eventLoop->apidata = state;
  15. return 0;
  16. }
  17. static int aeApiResize(aeEventLoop *eventLoop, int setsize) {
  18. /* Just ensure we have enough room in the fd_set type. */
  19. if (setsize >= FD_SETSIZE) return -1;
  20. return 0;
  21. }
  22. static void aeApiFree(aeEventLoop *eventLoop) {
  23. zfree(eventLoop->apidata);
  24. }
  25. static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {
  26. aeApiState *state = eventLoop->apidata;
  27. if (mask & AE_READABLE) FD_SET(fd,&state->rfds);
  28. if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds);
  29. return 0;
  30. }
  31. static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) {
  32. aeApiState *state = eventLoop->apidata;
  33. if (mask & AE_READABLE) FD_CLR(fd,&state->rfds);
  34. if (mask & AE_WRITABLE) FD_CLR(fd,&state->wfds);
  35. }
  36. static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {
  37. aeApiState *state = eventLoop->apidata;
  38. int retval, j, numevents = 0;
  39. memcpy(&state->_rfds,&state->rfds,sizeof(fd_set));
  40. memcpy(&state->_wfds,&state->wfds,sizeof(fd_set));
  41. retval = select(eventLoop->maxfd+1,
  42. &state->_rfds,&state->_wfds,NULL,tvp);
  43. if (retval > 0) {
  44. for (j = 0; j <= eventLoop->maxfd; j++) {
  45. int mask = 0;
  46. aeFileEvent *fe = &eventLoop->events[j];
  47. if (fe->mask == AE_NONE) continue;
  48. if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds))
  49. mask |= AE_READABLE;
  50. if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds))
  51. mask |= AE_WRITABLE;
  52. eventLoop->fired[numevents].fd = j;
  53. eventLoop->fired[numevents].mask = mask;
  54. numevents++;
  55. }
  56. }
  57. return numevents;
  58. }
  59. static char *aeApiName(void) {
  60. return "select";
  61. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载