PageRenderTime 41ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/common/lock/FileLock.cpp

https://gitlab.com/github-cloud-corporation/cynara
C++ | 88 lines | 49 code | 18 blank | 21 comment | 8 complexity | e31eb0851f4f0c9871787d3b4f3fdeea MD5 | raw file
  1. /*
  2. * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /**
  17. * @file src/common/lock/FileLock.cpp
  18. * @author Aleksander Zdyb <a.zdyb@samsung.com>
  19. * @version 1.0
  20. * @brief A class for acquiring and holding file lock
  21. */
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <string.h>
  25. #include <sys/file.h>
  26. #include <sys/stat.h>
  27. #include <sys/types.h>
  28. #include <unistd.h>
  29. #include <exceptions/CannotCreateFileException.h>
  30. #include <exceptions/FileLockAcquiringException.h>
  31. #include <log/log.h>
  32. #include "FileLock.h"
  33. namespace Cynara {
  34. Lockable::Lockable(const std::string &lockFilename) {
  35. m_fd = TEMP_FAILURE_RETRY(::open(lockFilename.c_str(), O_RDONLY));
  36. if (m_fd < 0) {
  37. LOGE("Could not open lock file <%s>", lockFilename.c_str());
  38. throw FileLockAcquiringException(errno);
  39. }
  40. LOGD("File lock file opened");
  41. }
  42. Lockable::~Lockable() {
  43. ::close(m_fd);
  44. }
  45. FileLock::FileLock(Lockable &lockable) : m_lockable(lockable) {}
  46. FileLock::~FileLock() {
  47. unlock();
  48. }
  49. bool FileLock::tryLock(void) {
  50. int lock = TEMP_FAILURE_RETRY(::flock(m_lockable.m_fd, LOCK_EX | LOCK_NB));
  51. if (lock == 0) {
  52. LOGI("File lock acquired");
  53. return true;
  54. } else if (errno == EWOULDBLOCK) {
  55. LOGI("File lock NOT acquired");
  56. return false;
  57. }
  58. throw FileLockAcquiringException(errno);
  59. }
  60. void FileLock::lock(void) {
  61. int lock = TEMP_FAILURE_RETRY(::flock(m_lockable.m_fd, LOCK_EX));
  62. if (lock == -1)
  63. throw FileLockAcquiringException(errno);
  64. LOGI("File lock acquired");
  65. }
  66. void FileLock::unlock(void) {
  67. LOGI("Releasing file lock");
  68. (void) TEMP_FAILURE_RETRY(::flock(m_lockable.m_fd, LOCK_UN));
  69. }
  70. } /* namespace Cynara */