Fix copyright lines
[folly.git] / folly / io / async / test / SocketPair.cpp
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
17 #include <folly/io/async/test/SocketPair.h>
18
19 #include <folly/Conv.h>
20 #include <folly/portability/Fcntl.h>
21 #include <folly/portability/Sockets.h>
22 #include <folly/portability/Unistd.h>
23
24 #include <errno.h>
25 #include <stdexcept>
26
27 namespace folly {
28
29 SocketPair::SocketPair(Mode mode) {
30   if (socketpair(PF_UNIX, SOCK_STREAM, 0, fds_) != 0) {
31     throw std::runtime_error(
32       folly::to<std::string>("test::SocketPair: failed create socket pair",
33                              errno));
34   }
35
36   if (mode == NONBLOCKING) {
37     if (fcntl(fds_[0], F_SETFL, O_NONBLOCK) != 0) {
38       throw std::runtime_error(
39         folly::to<std::string>("test::SocketPair: failed to set non-blocking "
40                                "read mode", errno));
41     }
42     if (fcntl(fds_[1], F_SETFL, O_NONBLOCK) != 0) {
43       throw std::runtime_error(
44         folly::to<std::string>("test::SocketPair: failed to set non-blocking "
45                                "write mode", errno));
46     }
47   }
48 }
49
50 SocketPair::~SocketPair() {
51   closeFD0();
52   closeFD1();
53 }
54
55 void SocketPair::closeFD0() {
56   if (fds_[0] >= 0) {
57     close(fds_[0]);
58     fds_[0] = -1;
59   }
60 }
61
62 void SocketPair::closeFD1() {
63   if (fds_[1] >= 0) {
64     close(fds_[1]);
65     fds_[1] = -1;
66   }
67 }
68
69 } // namespace folly