Apache Mesos
open.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_OPEN_HPP__
14 #define __STOUT_OS_OPEN_HPP__
15 
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 
19 #include <string>
20 
21 #include <stout/error.hpp>
22 #include <stout/nothing.hpp>
23 #include <stout/try.hpp>
24 
25 #include <stout/os/close.hpp>
26 #include <stout/os/fcntl.hpp>
27 #include <stout/os/int_fd.hpp>
28 
29 #ifdef __WINDOWS__
31 #endif // __WINDOWS__
32 
33 #ifndef O_CLOEXEC
34 #error "missing O_CLOEXEC support on this platform"
35 // NOTE: On Windows, `fnctl.hpp` defines `O_CLOEXEC` to a no-op.
36 #endif
37 
38 namespace os {
39 
40 inline Try<int_fd> open(const std::string& path, int oflag, mode_t mode = 0)
41 {
42 #ifdef __WINDOWS__
43  std::wstring longpath = ::internal::windows::longpath(path);
44  // By default, Windows will perform "text translation" meaning that it will
45  // automatically write CR/LF instead of LF line feeds. To prevent this, and
46  // use the POSIX semantics, we open with `O_BINARY`.
47  //
48  // Also by default, we will mimic the Windows (non-CRT) APIs and make all
49  // opened handles non-inheritable.
50  int_fd fd = ::_wopen(longpath.data(), oflag | O_BINARY | O_NOINHERIT, mode);
51 #else
52  int_fd fd = ::open(path.c_str(), oflag, mode);
53 #endif // __WINDOWS__
54  if (fd < 0) {
55  return ErrnoError();
56  }
57 
58  return fd;
59 }
60 
61 } // namespace os {
62 
63 #endif // __STOUT_OS_OPEN_HPP__
Definition: path.hpp:26
Definition: check.hpp:33
Definition: errorbase.hpp:49
Definition: posix_signalhandler.hpp:23
int mode_t
Definition: windows.hpp:183
Try< int_fd > open(const std::string &path, int oflag, mode_t mode=0)
Definition: open.hpp:40
Try< mode_t > mode(const std::string &path, const FollowSymlink follow=FollowSymlink::FOLLOW_SYMLINK)
Definition: stat.hpp:126
std::wstring longpath(const std::string &path)
Definition: longpath.hpp:38
int int_fd
Definition: int_fd.hpp:35