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 bool CallFlockOnFileWithFlag(const int fd, int flag) { |
| 14 int ret; |
| 15 if ((ret = TEMP_FAILURE_RETRY(flock(fd, flag))) < 0) { |
| 16 LOG(ERROR) << "Error locking " << fd << " error = " << strerror(errno); |
| 17 return false; |
| 18 } |
| 19 |
| 20 return true; |
| 21 } |
| 22 |
| 23 } // namespace |
| 24 |
| 25 namespace chromecast { |
| 26 |
| 27 int OpenAndLockFile(const base::FilePath& path) { |
| 28 int fd; |
| 29 const char* file = path.value().c_str(); |
| 30 |
| 31 if ((fd = open(file, O_RDONLY)) < 0) { |
| 32 LOG(ERROR) << "Error opening " << file << " error = " << strerror(errno); |
| 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 |