2 * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
18 * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
22 #include "file-lock.h"
25 #include <sys/types.h>
34 #include <stringify.h>
40 // TODO replace it with custom exception when they are implemented
41 template <typename... Args>
42 std::runtime_error io_exception(const Args&... args)
44 return std::runtime_error(Stringify()(args...));
47 } // namespace anonymous
49 FileLock::FileLock(const char* const file)
52 m_lockFd = TEMP_FAILURE_RETRY(creat(file, 0644));
54 throw io_exception("Cannot open lock file. Errno: ", strerror(errno));
57 if (-1 == lockf(m_lockFd, F_TLOCK, 0)) {
58 if (errno == EACCES || errno == EAGAIN)
59 throw io_exception("Can't acquire lock. Another instance must be running.");
61 throw io_exception("Can't acquire lock. Errno: ", strerror(errno));
64 std::string pid = std::to_string(getpid());
66 ssize_t written = TEMP_FAILURE_RETRY(write(m_lockFd, pid.c_str(), pid.size()));
67 if (-1 == written || static_cast<ssize_t>(pid.size()) > written)
68 throw io_exception("Can't write file lock. Errno: ", strerror(errno));
70 int ret = fsync(m_lockFd);
72 throw io_exception("Fsync failed. Errno: ",strerror(errno));
77 // this will also release the lock