Apache Mesos
fcntl.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_POSIX_FCNTL_HPP__
14 #define __STOUT_OS_POSIX_FCNTL_HPP__
15 
16 #include <fcntl.h>
17 
18 #include <stout/error.hpp>
19 #include <stout/nothing.hpp>
20 #include <stout/try.hpp>
21 
22 
23 // TODO(jieyu): Consider introducing a general os::fcntl function
24 // which allows us to get/set multiple flags in one call.
25 namespace os {
26 
27 inline Try<Nothing> cloexec(int fd)
28 {
29  int flags = ::fcntl(fd, F_GETFD);
30 
31  if (flags == -1) {
32  return ErrnoError();
33  }
34 
35  if (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
36  return ErrnoError();
37  }
38 
39  return Nothing();
40 }
41 
42 
43 inline Try<Nothing> unsetCloexec(int fd)
44 {
45  int flags = ::fcntl(fd, F_GETFD);
46 
47  if (flags == -1) {
48  return ErrnoError();
49  }
50 
51  if (::fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) == -1) {
52  return ErrnoError();
53  }
54 
55  return Nothing();
56 }
57 
58 
59 inline Try<bool> isCloexec(int fd)
60 {
61  int flags = ::fcntl(fd, F_GETFD);
62 
63  if (flags == -1) {
64  return ErrnoError();
65  }
66 
67  return (flags & FD_CLOEXEC) != 0;
68 }
69 
70 
71 inline Try<Nothing> nonblock(int fd)
72 {
73  int flags = ::fcntl(fd, F_GETFL);
74 
75  if (flags == -1) {
76  return ErrnoError();
77  }
78 
79  if (::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
80  return ErrnoError();
81  }
82 
83  return Nothing();
84 }
85 
86 
87 inline Try<bool> isNonblock(int fd)
88 {
89  int flags = ::fcntl(fd, F_GETFL);
90 
91  if (flags == -1) {
92  return ErrnoError();
93  }
94 
95  return (flags & O_NONBLOCK) != 0;
96 }
97 
98 } // namespace os {
99 
100 #endif // __STOUT_OS_POSIX_FCNTL_HPP__
constexpr int O_NONBLOCK
Definition: open.hpp:31
Definition: nothing.hpp:16
Definition: check.hpp:33
Try< bool > isNonblock(int fd)
Definition: fcntl.hpp:87
Try< bool > isCloexec(int fd)
Definition: fcntl.hpp:59
Definition: errorbase.hpp:50
Definition: posix_signalhandler.hpp:23
Try< Nothing > nonblock(int fd)
Definition: fcntl.hpp:71
Try< Nothing > cloexec(int fd)
Definition: fcntl.hpp:27
Try< Nothing > unsetCloexec(int fd)
Definition: fcntl.hpp:43
Definition: parse.hpp:33