Apache Mesos
strerror.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_STRERROR_HPP__
14 #define __STOUT_OS_STRERROR_HPP__
15 
16 #include <errno.h>
17 #include <string.h>
18 
19 #include <string>
20 
21 #ifdef __WINDOWS__
22 #include <stout/windows.hpp>
23 #endif // __WINDOWS__
24 
25 namespace os {
26 
30 inline std::string strerror(int errno_)
31 {
32  // There are two versions of strerror_r that need to be handled
33  // based on the feature test macros below.
34 #if !defined(__GLIBC__) || \
35  ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && \
36  !defined(_GNU_SOURCE))
37  // (1) We have the XSI-compliant version which returns an error code.
38  size_t size = 1024;
39  char* buffer = new char[size];
40 
41  while (true) {
42  if (::strerror_r(errno_, buffer, size) == ERANGE) {
43  delete[] buffer;
44  size *= 2;
45  buffer = new char[size];
46  } else {
47  const std::string message = buffer;
48  delete[] buffer;
49  return message;
50  }
51  }
52 #else
53  // (2) We have the GNU-specific version which returns a char*.
54  // For known error codes, strerror_r will not use the caller
55  // provided buffer and will instead return a pointer to
56  // internal storage. The buffer provided by the caller is only
57  // only used for unknown error messages. So, we ensure that
58  // the buffer can hold "Unknown error <20-digit 8-byte number>".
59  // Note that the buffer will include a truncated message if the
60  // buffer is not long enough.
61  char buffer[1024];
62  return ::strerror_r(errno_, buffer, 1024);
63 #endif
64 }
65 
66 } // namespace os {
67 #endif // __STOUT_OS_STRERROR_HPP__
std::string strerror(int errno_)
A thread-safe version of strerror.
Definition: strerror.hpp:30
Try< Bytes > size(const std::string &path, const FollowSymlink follow=FollowSymlink::FOLLOW_SYMLINK)
Definition: stat.hpp:130
Definition: posix_signalhandler.hpp:23
auto strerror_r(int errnum, char *buffer, size_t length) -> decltype(strerror_s(buffer, length, errnum))
Definition: windows.hpp:337