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 <stout/error.hpp>
17 #include <stout/nothing.hpp>
18 #include <stout/try.hpp>
19 
20 #include <stout/os/int_fd.hpp>
21 
23 
24 namespace os {
25 
26 inline Try<Nothing> close(const int_fd& fd)
27 {
28  switch (fd.type()) {
30  if (!fd.is_valid()) {
31  // NOTE: We return early here because
32  // `CloseHandle(INVALID_HANDLE_VALUE)` will not return an error, but
33  // instead (sometimes) triggers the invalid parameter handler, thus
34  // throwing an exception. We'd rather return an error.
35  return WindowsError(ERROR_INVALID_HANDLE);
36  }
37 
38  if (::CloseHandle(fd) == FALSE) {
39  return WindowsError();
40  }
41 
42  return Nothing();
43  }
45  // NOTE: Since closing an unconnected socket is not an error in POSIX,
46  // we simply ignore it here.
47  if (::shutdown(fd, SD_BOTH) == SOCKET_ERROR &&
48  WSAGetLastError() != WSAENOTCONN) {
49  return WindowsSocketError("Failed to shutdown a socket");
50  }
51 
52  if (::closesocket(fd) == SOCKET_ERROR) {
53  return WindowsSocketError("Failed to close a socket");
54  }
55 
56  return Nothing();
57  }
58  }
59 
60  UNREACHABLE();
61 }
62 
63 } // namespace os {
64 
65 #endif // __STOUT_OS_WINDOWS_CLOSE_HPP__
Definition: nothing.hpp:16
Definition: check.hpp:33
Definition: error.hpp:123
Definition: error.hpp:108
Definition: posix_signalhandler.hpp:23
Try< Nothing > close(int fd)
Definition: close.hpp:24
#define UNREACHABLE()
Definition: unreachable.hpp:22
int int_fd
Definition: int_fd.hpp:35