Serenity Operating System
1/*
2 * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibCore/Directory.h>
8#include <LibCore/LockFile.h>
9#include <errno.h>
10#include <fcntl.h>
11#include <sys/file.h>
12#include <unistd.h>
13
14namespace Core {
15
16LockFile::LockFile(char const* filename, Type type)
17 : m_filename(filename)
18{
19 if (Core::Directory::create(LexicalPath(m_filename).parent(), Core::Directory::CreateDirectories::Yes).is_error())
20 return;
21
22 m_fd = open(filename, O_RDONLY | O_CREAT | O_CLOEXEC, 0666);
23 if (m_fd == -1) {
24 m_errno = errno;
25 return;
26 }
27
28 if (flock(m_fd, LOCK_NB | ((type == Type::Exclusive) ? LOCK_EX : LOCK_SH)) == -1) {
29 m_errno = errno;
30 close(m_fd);
31 m_fd = -1;
32 }
33}
34
35LockFile::~LockFile()
36{
37 release();
38}
39
40bool LockFile::is_held() const
41{
42 return m_fd != -1;
43}
44
45void LockFile::release()
46{
47 if (m_fd == -1)
48 return;
49
50 unlink(m_filename);
51 flock(m_fd, LOCK_NB | LOCK_UN);
52 close(m_fd);
53
54 m_fd = -1;
55}
56
57}