dinit-socket.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef _DINIT_SOCKET_H_INCLUDED
  2. #define _DINIT_SOCKET_H_INCLUDED
  3. #include <sys/socket.h>
  4. #include <fcntl.h>
  5. namespace {
  6. #if !defined(SOCK_NONBLOCK) && !defined(SOCK_CLOEXEC)
  7. // make our own accept4 on systems that don't have it:
  8. constexpr int SOCK_NONBLOCK = 1;
  9. constexpr int SOCK_CLOEXEC = 2;
  10. inline int dinit_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
  11. {
  12. int fd = accept(sockfd, addr, addrlen);
  13. if (fd == -1) {
  14. return -1;
  15. }
  16. if (flags & SOCK_CLOEXEC) fcntl(fd, F_SETFD, FD_CLOEXEC);
  17. if (flags & SOCK_NONBLOCK) fcntl(fd, F_SETFL, O_NONBLOCK);
  18. return fd;
  19. }
  20. inline int dinit_socket(int domain, int type, int protocol, int flags)
  21. {
  22. int fd = socket(domain, type, protocol);
  23. if (fd == -1) {
  24. return -1;
  25. }
  26. if (flags & SOCK_CLOEXEC) fcntl(fd, F_SETFD, FD_CLOEXEC);
  27. if (flags & SOCK_NONBLOCK) fcntl(fd, F_SETFL, O_NONBLOCK);
  28. return fd;
  29. }
  30. inline int dinit_socketpair(int domain, int type, int protocol, int socket_vector[2], int flags)
  31. {
  32. int r = socketpair(domain, type, protocol, socket_vector);
  33. if (r == -1) {
  34. return -1;
  35. }
  36. if (flags & SOCK_CLOEXEC) {
  37. fcntl(socket_vector[0], F_SETFD, FD_CLOEXEC);
  38. fcntl(socket_vector[1], F_SETFD, FD_CLOEXEC);
  39. }
  40. if (flags & SOCK_NONBLOCK) {
  41. fcntl(socket_vector[0], F_SETFL, O_NONBLOCK);
  42. fcntl(socket_vector[1], F_SETFL, O_NONBLOCK);
  43. }
  44. return 0;
  45. }
  46. #else
  47. inline int dinit_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
  48. {
  49. return accept4(sockfd, addr, addrlen, flags);
  50. }
  51. inline int dinit_socket(int domain, int type, int protocol, int flags)
  52. {
  53. return socket(domain, type | flags, protocol);
  54. }
  55. inline int dinit_socketpair(int domain, int type, int protocol, int socket_vector[2], int flags)
  56. {
  57. return socketpair(domain, type | flags, protocol, socket_vector);
  58. }
  59. #endif
  60. }
  61. #endif