henrike@webrtc.org | f7795df | 2014-05-13 18:00:26 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2009 The WebRTC Project Authors. All rights reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | #ifndef WEBRTC_BASE_FILELOCK_H_ |
| 12 | #define WEBRTC_BASE_FILELOCK_H_ |
| 13 | |
| 14 | #include <string> |
| 15 | |
| 16 | #include "webrtc/base/constructormagic.h" |
| 17 | #include "webrtc/base/scoped_ptr.h" |
| 18 | |
| 19 | namespace rtc { |
| 20 | |
| 21 | class FileStream; |
| 22 | |
| 23 | // Implements a very simple cross process lock based on a file. |
| 24 | // When Lock(...) is called we try to open/create the file in read/write |
| 25 | // mode without any sharing. (Or locking it with flock(...) on Unix) |
| 26 | // If the process crash the OS will make sure that the file descriptor |
| 27 | // is released and another process can accuire the lock. |
| 28 | // This doesn't work on ancient OSX/Linux versions if used on NFS. |
| 29 | // (Nfs-client before: ~2.6 and Linux Kernel < 2.6.) |
| 30 | class FileLock { |
| 31 | public: |
| 32 | virtual ~FileLock(); |
| 33 | |
| 34 | // Attempts to lock the file. The caller owns the returned |
| 35 | // lock object. Returns NULL if the file already was locked. |
| 36 | static FileLock* TryLock(const std::string& path); |
| 37 | void Unlock(); |
| 38 | |
| 39 | protected: |
| 40 | FileLock(const std::string& path, FileStream* file); |
| 41 | |
| 42 | private: |
| 43 | void MaybeUnlock(); |
| 44 | |
| 45 | std::string path_; |
| 46 | scoped_ptr<FileStream> file_; |
| 47 | |
| 48 | DISALLOW_EVIL_CONSTRUCTORS(FileLock); |
| 49 | }; |
| 50 | |
| 51 | } // namespace rtc |
| 52 | |
| 53 | #endif // WEBRTC_BASE_FILELOCK_H_ |