Branch data Line data Source code
1 : : /* 2 : : ** Copyright (C) 2020 CERN 3 : : ** 4 : : ** This software is provided 'as-is', without any express or implied 5 : : ** warranty. In no event will the authors be held liable for any damages 6 : : ** arising from the use of this software. 7 : : ** 8 : : ** Permission is granted to anyone to use this software for any purpose, 9 : : ** including commercial applications, and to alter it and redistribute it 10 : : ** freely, subject to the following restrictions: 11 : : ** 12 : : ** 1. The origin of this software must not be misrepresented; you must not 13 : : ** claim that you wrote the original software. If you use this software 14 : : ** in a product, an acknowledgment in the product documentation would be 15 : : ** appreciated but is not required. 16 : : ** 2. Altered source versions must be plainly marked as such, and must not be 17 : : ** misrepresented as being the original software. 18 : : ** 3. This notice may not be removed or altered from any source distribution. 19 : : ** 20 : : ** Created on: 2020-09-01T14:21:21+02:00 21 : : ** Author: Sylvain Fargier <sfargier> <sylvain.fargier@cern.ch> 22 : : ** 23 : : */ 24 : : 25 : : #ifndef FLOCK_HPP__ 26 : : #define FLOCK_HPP__ 27 : : 28 : : #include <atomic> 29 : : #include <string> 30 : : 31 : : namespace ccut { 32 : : 33 : : /** 34 : : * @brief flock(2) c++ wrapper 35 : : */ 36 : : class Flock 37 : : { 38 : : public: 39 : : enum Mode 40 : : { 41 : : Shared, 42 : : Exclusive 43 : : }; 44 : : 45 : : /** 46 : : * @throws Exception on open failure 47 : : */ 48 : : explicit Flock(Mode mode = Mode::Shared, 49 : : const std::string &fileName = DefaultLock); 50 : : ~Flock(); 51 : : Flock(const Flock &) = delete; 52 : : Flock &operator=(const Flock &) = delete; 53 : : 54 : : /** 55 : : * @brief try to lock in non-blocking mode 56 : : * @return true if lock is held 57 : : * @throws Exception on error 58 : : */ 59 : : bool try_lock(); 60 : : 61 : : /** 62 : : * @brief lock the file-lock 63 : : * @throws Exception on error 64 : : */ 65 : : void lock(); 66 : : 67 : : /** 68 : : * @brief unlock the file-lock 69 : : */ 70 : : void unlock(); 71 : : 72 : 1 : inline Mode mode() const { return m_mode; } 73 : : 74 : 16 : inline bool isLocked() const { return m_locked.load() == 1; } 75 : : 76 : 1 : inline const std::string &fileName() const { return m_fileName; } 77 : : 78 : : static const std::string DefaultLock; 79 : : 80 : : protected: 81 : : const Mode m_mode; 82 : : const std::string m_fileName; 83 : : std::atomic<int> m_locked; 84 : : int m_fd; 85 : : }; 86 : : 87 : : } // namespace ccut 88 : : 89 : : #endif