2 * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
4 * Contact: Rafal Krypa <r.krypa@samsung.com>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
20 * @author Sebastian Grabowski (s.grabowski@samsung.com)
22 * @brief Implementation of simple file locking for a service
24 /* vim: set ts=4 et sw=4 tw=78 : */
27 #include <dpl/log/log.h>
29 #include "file-lock.h"
31 namespace SecurityManager {
33 char const * const SERVICE_LOCK_FILE = tzplatform_mkpath3(TZ_SYS_RUN,
35 "security-manager.lock");
37 FileLocker::FileLocker(const std::string &lockFile, bool blocking)
39 if (lockFile.empty()) {
40 LogError("File name can not be empty.");
41 ThrowMsg(FileLocker::Exception::LockFailed,
42 "File name can not be empty.");
46 m_blocking = blocking;
47 m_lockFile = lockFile;
49 } catch (FileLocker::Exception::Base &e) {
50 LogError("Failed to lock " << lockFile << " file: "
52 ThrowMsg(FileLocker::Exception::LockFailed,
53 "Failed to lock " << lockFile << " file: "
58 FileLocker::~FileLocker()
63 bool FileLocker::Locked()
68 void FileLocker::Lock()
73 if (!std::ifstream(m_lockFile).good())
74 std::ofstream(m_lockFile.c_str());
75 m_flock = boost::interprocess::file_lock(m_lockFile.c_str());
80 m_locked = m_flock.try_lock();
81 } catch (const std::exception &e) {
82 ThrowMsg(FileLocker::Exception::LockFailed,
83 "Error while locking a file.");
86 LogDebug("We have a lock on " << m_lockFile << " file.");
89 ThrowMsg(FileLocker::Exception::LockFailed,
90 "Unable to lock file.");
92 LogDebug("Impossible to lock a file now.");
97 void FileLocker::Unlock()
101 LogDebug("Lock released.");
105 } // namespace SecurityManager