Apache Mesos
fsync.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_FSYNC_HPP__
14 #define __STOUT_OS_POSIX_FSYNC_HPP__
15 
16 #include <unistd.h>
17 
18 #include <string>
19 
20 #include <stout/nothing.hpp>
21 #include <stout/try.hpp>
22 
23 #include <stout/os/close.hpp>
24 #include <stout/os/int_fd.hpp>
25 #include <stout/os/open.hpp>
26 
27 namespace os {
28 
29 inline Try<Nothing> fsync(int fd)
30 {
31  if (::fsync(fd) == -1) {
32  return ErrnoError();
33  }
34 
35  return Nothing();
36 }
37 
38 
39 // A wrapper function for the above `fsync()` with opening and closing the file.
40 // NOTE: This function is POSIX only and can be used to commit changes to a
41 // directory (e.g., renaming files) to the filesystem.
42 inline Try<Nothing> fsync(const std::string& path)
43 {
44  Try<int_fd> fd = os::open(path, O_RDONLY | O_CLOEXEC);
45 
46  if (fd.isError()) {
47  return Error(fd.error());
48  }
49 
50  Try<Nothing> result = fsync(fd.get());
51 
52  // We ignore the return value of `close()` since any I/O-related failure
53  // scenarios would already have been triggered by `open()` or `fsync()`.
54  os::close(fd.get());
55 
56  return result;
57 }
58 
59 } // namespace os {
60 
61 #endif // __STOUT_OS_POSIX_FSYNC_HPP__
Definition: path.hpp:29
Definition: nothing.hpp:16
Definition: errorbase.hpp:36
T & get()&
Definition: try.hpp:80
Definition: check.hpp:33
Try< int_fd > open(const std::string &path, int oflag, mode_t mode=0)
Definition: open.hpp:35
Definition: errorbase.hpp:50
Definition: posix_signalhandler.hpp:23
constexpr int O_CLOEXEC
Definition: open.hpp:41
Try< Nothing > close(int fd)
Definition: close.hpp:24
static Try error(const E &e)
Definition: try.hpp:43
Try< Nothing > fsync(int fd)
Definition: fsync.hpp:29
bool isError() const
Definition: try.hpp:78