Apache Mesos
dup.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_WINDOWS_DUP_HPP__
14 #define __STOUT_OS_WINDOWS_DUP_HPP__
15 
16 #include <stout/error.hpp>
17 #include <stout/try.hpp>
18 #include <stout/unreachable.hpp>
19 #include <stout/windows.hpp> // For `WinSock2.h`.
20 
21 #include <stout/os/int_fd.hpp>
22 
23 namespace os {
24 
25 inline Try<int_fd> dup(const int_fd& fd)
26 {
27  switch (fd.type()) {
29  HANDLE duplicate = INVALID_HANDLE_VALUE;
30  const BOOL result = ::DuplicateHandle(
31  ::GetCurrentProcess(), // Source process == current.
32  fd, // Handle to duplicate.
33  ::GetCurrentProcess(), // Target process == current.
34  &duplicate,
35  0, // Ignored (DUPLICATE_SAME_ACCESS).
36  FALSE, // Non-inheritable handle.
37  DUPLICATE_SAME_ACCESS); // Same access level as source.
38 
39  if (result == FALSE) {
40  return WindowsError();
41  }
42 
43  WindowsFD dup_fd(fd);
44  dup_fd.handle_ = duplicate;
45  return dup_fd;
46  }
48  WSAPROTOCOL_INFOW info;
49  const int result =
50  ::WSADuplicateSocketW(fd, ::GetCurrentProcessId(), &info);
51  if (result != 0) {
52  return SocketError();
53  }
54 
55  SOCKET duplicate = ::WSASocketW(0, 0, 0, &info, 0, 0);
56  if (duplicate == INVALID_SOCKET) {
57  return WindowsSocketError();
58  }
59 
60  WindowsFD dup_fd(fd);
61  dup_fd.socket_ = duplicate;
62  return dup_fd;
63  }
64  }
65 
66  UNREACHABLE();
67 }
68 
69 } // namespace os {
70 
71 #endif // __STOUT_OS_WINDOWS_DUP_HPP__
SOCKET socket_
Definition: fd.hpp:242
Definition: fd.hpp:52
Definition: check.hpp:33
Definition: error.hpp:123
Definition: error.hpp:108
Definition: posix_signalhandler.hpp:23
ErrnoError SocketError
Definition: error.hpp:33
constexpr Handle HANDLE
Definition: ingress.hpp:37
#define UNREACHABLE()
Definition: unreachable.hpp:22
int int_fd
Definition: int_fd.hpp:35
Try< int > dup(int fd)
Definition: dup.hpp:23
HANDLE handle_
Definition: fd.hpp:241