asio.hpp 960 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #ifndef _FY_ASIO_H_
  2. #define _FY_ASIO_H_
  3. #include <poll.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. namespace base {
  7. namespace asio {
  8. /**
  9. * -1 error
  10. * 0 timeout
  11. * >0 get event
  12. */
  13. inline int readable(int fd, int timeout_ms) {
  14. int ret = -1;
  15. struct pollfd pfd;
  16. memset(&pfd, 0, sizeof(pfd));
  17. pfd.fd = fd;
  18. pfd.events = POLLIN;
  19. // retry again for EINTR
  20. for (int i = 0; i < 2; i++) {
  21. ret = ::poll(&pfd, 1, timeout_ms);
  22. if (-1 == ret && EINTR == errno)
  23. continue;
  24. break;
  25. }
  26. return ret;
  27. }
  28. /**
  29. * -1 error
  30. * 0 timeout
  31. * >0 get event
  32. */
  33. inline int writable(int fd, int timeout_ms) {
  34. int ret = -1;
  35. struct pollfd pfd;
  36. memset(&pfd, 0, sizeof(pfd));
  37. pfd.fd = fd;
  38. pfd.events = POLLOUT;
  39. // retry again for EINTR
  40. for (int i = 0; i < 2; i++) {
  41. ret = ::poll(&pfd, 1, timeout_ms);
  42. if (-1 == ret && EINTR == errno)
  43. continue;
  44. break;
  45. }
  46. return ret;
  47. }
  48. } /* namespace asio */
  49. } /* namespace sup */
  50. #endif