OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "chromecast/base/file_utils.h" |
| 6 |
| 7 #include <errno.h> |
| 8 #include <fcntl.h> |
| 9 #include <sys/file.h> |
| 10 |
| 11 namespace { |
| 12 |
| 13 // Calls flock on valid file descriptor |fd| with flag |flag|. Returns true |
| 14 // on success, false on failure. |
| 15 bool CallFlockOnFileWithFlag(const int fd, int flag) { |
| 16 int ret = -1; |
| 17 if ((ret = TEMP_FAILURE_RETRY(flock(fd, flag))) < 0) |
| 18 PLOG(ERROR) << "Error locking " << fd; |
| 19 |
| 20 return !ret; |
| 21 } |
| 22 |
| 23 } // namespace |
| 24 |
| 25 namespace chromecast { |
| 26 |
| 27 int OpenAndLockFile(const base::FilePath& path, bool write) { |
| 28 int fd = -1; |
| 29 const char* file = path.value().c_str(); |
| 30 |
| 31 if ((fd = open(file, write ? O_RDWR : O_RDONLY)) < 0) { |
| 32 PLOG(ERROR) << "Error opening " << file; |
| 33 } else if (!CallFlockOnFileWithFlag(fd, LOCK_EX)) { |
| 34 close(fd); |
| 35 fd = -1; |
| 36 } |
| 37 |
| 38 return fd; |
| 39 } |
| 40 |
| 41 bool UnlockAndCloseFile(const int fd) { |
| 42 if (!CallFlockOnFileWithFlag(fd, LOCK_UN)) |
| 43 return false; |
| 44 return !close(fd); |
| 45 } |
| 46 |
| 47 } // namespace chromecast |
OLD | NEW |