LockFile.cpp 1.0 KB

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