async.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /** @file async.c
  2. */
  3. #ifdef HAVE_CONFIG_H
  4. #include "config.h"
  5. #endif /* HAVE_CONFIG_H */
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <assert.h>
  11. #include <unistd.h>
  12. #include <errno.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <fcntl.h>
  16. #include "faux/faux.h"
  17. #include "faux/str.h"
  18. #include "faux/net.h"
  19. #include "faux/async.h"
  20. #include "private.h"
  21. /** @brief Create new async I/O object.
  22. *
  23. * Constructor gets associated file descriptor to operate on it. File
  24. * descriptor must be nonblocked. If not so then constructor will set
  25. * nonblock flag itself.
  26. *
  27. * @param [in] fd File descriptor.
  28. * @return Allocated object or NULL on error.
  29. */
  30. faux_async_t *faux_async_new(int fd)
  31. {
  32. faux_async_t *async = NULL;
  33. int fflags = 0;
  34. // Prepare FD
  35. if (fd < 0) // Illegal fd
  36. return NULL;
  37. if ((fflags = fcntl(fd, F_GETFL)) == -1)
  38. return NULL;
  39. if (fcntl(fd, F_SETFL, fflags | O_NONBLOCK) == -1)
  40. return NULL;
  41. async = faux_zmalloc(sizeof(*async));
  42. assert(async);
  43. if (!async)
  44. return NULL;
  45. // Init
  46. async->fd = fd;
  47. return async;
  48. }
  49. /** @brief Free async I/O object.
  50. *
  51. * @param [in] Async I/O object.
  52. */
  53. void faux_async_free(faux_async_t *async)
  54. {
  55. if (!async)
  56. return;
  57. faux_free(async);
  58. }
  59. /** @brief Get file descriptor from async I/O object.
  60. *
  61. * @param [in] async Allocated and initialized async I/O object.
  62. * @return Serviced file descriptor.
  63. */
  64. int faux_async_fd(const faux_async_t *async)
  65. {
  66. assert(async);
  67. if (!async)
  68. return -1;
  69. return async->fd;
  70. }