mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 14:28:12 +00:00
LibCore: Add LockFile, a filesystem based mutex
This API wraps flock(2) and also handles the file creation and deletion when the LockFile goes out of scope.
This commit is contained in:
parent
7da12f0faf
commit
fdcfd2816e
3 changed files with 90 additions and 0 deletions
57
Userland/Libraries/LibCore/LockFile.cpp
Normal file
57
Userland/Libraries/LibCore/LockFile.cpp
Normal file
|
@ -0,0 +1,57 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Peter Elliott <pelliott@ualberta.ca>
|
||||
*
|
||||
* 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, 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;
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue