summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore/LockFile.cpp
blob: 8fde1434420d3a0f60281da1c7796be944604a7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
 * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/File.h>
#include <LibCore/LockFile.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>

namespace Core {

LockFile::LockFile(char const* filename, Type type)
    : m_filename(filename)
{
    if (!Core::File::ensure_parent_directories(m_filename))
        return;

    m_fd = open(filename, O_RDONLY | O_CREAT | O_CLOEXEC, 0666);
    if (m_fd == -1) {
        m_errno = errno;
        return;
    }

    if (flock(m_fd, LOCK_NB | ((type == Type::Exclusive) ? LOCK_EX : LOCK_SH)) == -1) {
        m_errno = errno;
        close(m_fd);
        m_fd = -1;
    }
}

LockFile::~LockFile()
{
    release();
}

bool LockFile::is_held() const
{
    return m_fd != -1;
}

void LockFile::release()
{
    if (m_fd == -1)
        return;

    unlink(m_filename);
    flock(m_fd, LOCK_NB | LOCK_UN);
    close(m_fd);

    m_fd = -1;
}

}