| 35 | } |
| 36 | |
| 37 | bool LockFile::lock(int64_t timeout) { |
| 38 | auto doFLock = [](String const& filename) -> shared_ptr<HANDLE> { |
| 39 | HANDLE handle = CreateFileW( |
| 40 | stringToUtf16(filename).get(), GENERIC_READ, 0, nullptr, OPEN_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, nullptr); |
| 41 | if (handle == INVALID_HANDLE_VALUE) { |
| 42 | if (GetLastError() == ERROR_SHARING_VIOLATION) |
| 43 | return {}; |
| 44 | throw StarException(strf("Could not open lock file {}, error code {}\n", filename, GetLastError())); |
| 45 | } |
| 46 | |
| 47 | return make_shared<HANDLE>(handle); |
| 48 | }; |
| 49 | |
| 50 | if (timeout == 0) { |
| 51 | m_handle = doFLock(m_filename); |
| 52 | return (bool)m_handle; |
| 53 | } else { |
| 54 | int64_t startTime = Time::monotonicMilliseconds(); |
| 55 | while (true) { |
| 56 | m_handle = doFLock(m_filename); |
| 57 | if (m_handle) |
| 58 | return true; |
| 59 | |
| 60 | if (timeout > 0 && Time::monotonicMilliseconds() - startTime > timeout) |
| 61 | return false; |
| 62 | |
| 63 | Thread::sleep(min(timeout / 4, MaximumSleepMillis)); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | void LockFile::unlock() { |
| 69 | if (m_handle) { |
no test coverage detected