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 #include "webrtc/base/filelock.h" 12 13 #include "webrtc/base/fileutils.h" 14 #include "webrtc/base/logging.h" 15 #include "webrtc/base/pathutils.h" 16 #include "webrtc/base/stream.h" 17 18 namespace rtc { 19 20 FileLock::FileLock(const std::string& path, FileStream* file) 21 : path_(path), file_(file) { 22 } 23 24 FileLock::~FileLock() { 25 MaybeUnlock(); 26 } 27 28 void FileLock::Unlock() { 29 LOG_F(LS_INFO); 30 MaybeUnlock(); 31 } 32 33 void FileLock::MaybeUnlock() { 34 if (file_) { 35 LOG(LS_INFO) << "Unlocking:" << path_; 36 file_->Close(); 37 Filesystem::DeleteFile(path_); 38 file_.reset(); 39 } 40 } 41 42 FileLock* FileLock::TryLock(const std::string& path) { 43 FileStream* stream = new FileStream(); 44 bool ok = false; 45 #if defined(WEBRTC_WIN) 46 // Open and lock in a single operation. 47 ok = stream->OpenShare(path, "a", _SH_DENYRW, NULL); 48 #else // WEBRTC_LINUX && !WEBRTC_ANDROID and WEBRTC_MAC && !defined(WEBRTC_IOS) 49 ok = stream->Open(path, "a", NULL) && stream->TryLock(); 50 #endif 51 if (ok) { 52 return new FileLock(path, stream); 53 } else { 54 // Something failed, either we didn't succeed to open the 55 // file or we failed to lock it. Anyway remove the heap 56 // allocated object and then return NULL to indicate failure. 57 delete stream; 58 return NULL; 59 } 60 } 61 62 } // namespace rtc 63