2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/File.h>
22 #include <folly/Exception.h>
23 #include <folly/FileUtil.h>
24 #include <folly/Format.h>
25 #include <folly/ScopeGuard.h>
27 #include <system_error>
29 #include <glog/logging.h>
38 File::File(int fd, bool ownsFd)
41 CHECK_GE(fd, -1) << "fd must be -1 or non-negative";
42 CHECK(fd != -1 || !ownsFd) << "cannot own -1";
45 File::File(const char* name, int flags, mode_t mode)
46 : fd_(::open(name, flags, mode))
49 throwSystemError(folly::format("open(\"{}\", {:#o}, 0{:#o}) failed",
50 name, flags, mode).fbstr());
55 File::File(File&& other)
57 , ownsFd_(other.ownsFd_) {
61 File& File::operator=(File&& other) {
68 closeNoThrow(); // ignore error
71 /* static */ File File::temporary() {
72 // make a temp file with tmpfile(), dup the fd, then return it in a File.
73 FILE* tmpFile = tmpfile();
74 checkFopenError(tmpFile, "tmpfile() failed");
75 SCOPE_EXIT { fclose(tmpFile); };
77 int fd = ::dup(fileno(tmpFile));
78 checkUnixError(fd, "dup() failed");
80 return File(fd, true);
90 void File::swap(File& other) {
93 swap(ownsFd_, other.ownsFd_);
96 void swap(File& a, File& b) {
100 File File::dup() const {
103 checkUnixError(fd, "dup() failed");
105 return File(fd, true);
112 if (!closeNoThrow()) {
113 throwSystemError("close() failed");
117 bool File::closeNoThrow() {
118 int r = ownsFd_ ? ::close(fd_) : 0;
123 void File::lock() { doLock(LOCK_EX); }
124 bool File::try_lock() { return doTryLock(LOCK_EX); }
125 void File::lock_shared() { doLock(LOCK_SH); }
126 bool File::try_lock_shared() { return doTryLock(LOCK_SH); }
128 void File::doLock(int op) {
129 checkUnixError(flockNoInt(fd_, op), "flock() failed (lock)");
132 bool File::doTryLock(int op) {
133 int r = flockNoInt(fd_, op | LOCK_NB);
134 // flock returns EWOULDBLOCK if already locked
135 if (r == -1 && errno == EWOULDBLOCK) return false;
136 checkUnixError(r, "flock() failed (try_lock)");
140 void File::unlock() {
141 checkUnixError(flockNoInt(fd_, LOCK_UN), "flock() failed (unlock)");
143 void File::unlock_shared() { unlock(); }