SocketPair.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/io/async/test/SocketPair.h>
  17. #include <folly/Conv.h>
  18. #include <folly/portability/Fcntl.h>
  19. #include <folly/portability/Sockets.h>
  20. #include <folly/portability/Unistd.h>
  21. #include <errno.h>
  22. #include <stdexcept>
  23. namespace folly {
  24. SocketPair::SocketPair(Mode mode) {
  25. if (socketpair(PF_UNIX, SOCK_STREAM, 0, fds_) != 0) {
  26. throw std::runtime_error(folly::to<std::string>(
  27. "test::SocketPair: failed create socket pair", errno));
  28. }
  29. if (mode == NONBLOCKING) {
  30. if (fcntl(fds_[0], F_SETFL, O_NONBLOCK) != 0) {
  31. throw std::runtime_error(folly::to<std::string>(
  32. "test::SocketPair: failed to set non-blocking "
  33. "read mode",
  34. errno));
  35. }
  36. if (fcntl(fds_[1], F_SETFL, O_NONBLOCK) != 0) {
  37. throw std::runtime_error(folly::to<std::string>(
  38. "test::SocketPair: failed to set non-blocking "
  39. "write mode",
  40. errno));
  41. }
  42. }
  43. }
  44. SocketPair::~SocketPair() {
  45. closeFD0();
  46. closeFD1();
  47. }
  48. void SocketPair::closeFD0() {
  49. if (fds_[0] >= 0) {
  50. close(fds_[0]);
  51. fds_[0] = -1;
  52. }
  53. }
  54. void SocketPair::closeFD1() {
  55. if (fds_[1] >= 0) {
  56. close(fds_[1]);
  57. fds_[1] = -1;
  58. }
  59. }
  60. } // namespace folly