2
* Copyright (C) 2015 Canonical Ltd.
4
* This program is free software: you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License version 3 as
6
* published by the Free Software Foundation.
8
* This program is distributed in the hope that it will be useful,
9
* but WITHOUT ANY WARRANTY; without even the implied warranty of
10
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
* GNU General Public License for more details.
13
* You should have received a copy of the GNU General Public License
14
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16
* Authored by: Michi Henning <michi.henning@canonical.com>
19
#include <internal/file_lock.h>
21
#include <unity/UnityExceptions.h>
39
int const AdvisoryFileLock::sleep_interval;
41
AdvisoryFileLock::AdvisoryFileLock(string const& path)
45
if ((fd_ = open(path_.c_str(), O_CREAT, 0444)) == -1)
47
throw FileException("AdvisoryFileLock::lock(): cannot open " + path_, errno);
51
bool AdvisoryFileLock::lock(chrono::milliseconds msecs)
55
throw LogicException("AdvisoryFileLock::lock(): locked already: " + path_);
59
if (msecs != chrono::milliseconds::zero())
63
int64_t remaining_time = msecs.count();
67
if ((rc = flock(fd_, mode)) == -1)
69
if (errno == EWOULDBLOCK)
71
this_thread::sleep_for(chrono::milliseconds(sleep_interval));
72
remaining_time -= sleep_interval;
76
throw FileException("AdvisoryFileLock::lock(): flock failed", errno); // LCOV_EXCL_LINE
80
while (rc == -1 && remaining_time > 0);
85
void AdvisoryFileLock::unlock()
89
throw LogicException("AdvisoryFileLock::unlock(): unlocked already: " + path_);
91
if (flock(fd_, LOCK_UN) == -1)
93
throw FileException("AdvisoryFileLock::unlock(): cannot unlock " + path_, errno); // LCOV_EXCL_LINE
98
AdvisoryFileLock::~AdvisoryFileLock()
106
} // namespace internal
108
} // namespace thumbnailer