Apache Mesos
close.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_CLOSE_HPP__
14 #define __STOUT_OS_WINDOWS_CLOSE_HPP__
15 
16 #include <errno.h>
17 
18 #include <stout/nothing.hpp>
19 #include <stout/try.hpp>
20 #include <stout/windows/error.hpp>
21 
22 #include <stout/os/windows/fd.hpp>
24 
25 namespace os {
26 
27 inline Try<Nothing> close(const WindowsFD& fd)
28 {
29  switch (fd.type()) {
30  case WindowsFD::FD_CRT:
31  case WindowsFD::FD_HANDLE: {
32  // We don't need to call `CloseHandle` on `fd.handle`, because calling
33  // `_close` on the corresponding CRT FD implicitly invokes `CloseHandle`.
34  if (::_close(fd.crt()) < 0) {
35  return ErrnoError();
36  }
37  break;
38  }
39  case WindowsFD::FD_SOCKET: {
40  // NOTE: Since closing an unconnected socket is not an error in POSIX,
41  // we simply ignore it here.
42  if (::shutdown(fd, SD_BOTH) == SOCKET_ERROR &&
43  WSAGetLastError() != WSAENOTCONN) {
44  return WindowsSocketError("Failed to shutdown a socket");
45  }
46  if (::closesocket(fd) == SOCKET_ERROR) {
47  return WindowsSocketError("Failed to close a socket");
48  }
49  break;
50  }
51  }
52  return Nothing();
53 }
54 
55 } // namespace os {
56 
57 #endif // __STOUT_OS_WINDOWS_CLOSE_HPP__
Definition: fd.hpp:54
Definition: nothing.hpp:16
Definition: fd.hpp:53
Type type() const
Definition: fd.hpp:121
Definition: fd.hpp:47
Definition: try.hpp:34
Definition: error.hpp:120
Definition: errorbase.hpp:49
Try< Nothing > close(int fd)
Definition: close.hpp:24
int crt() const
Definition: fd.hpp:97
Definition: fd.hpp:52