| 48 | } |
| 49 | |
| 50 | bool FileLock::fcntlLock(LockType lockType, bool wait, bool unLockFirstIfNeeded, bool *tryAgain) { |
| 51 | m_lockInfo.l_type = LockType2FlockType(lockType); |
| 52 | auto FcntlLockOp = m_isAshmem ? F_SETLK : F_OFD_SETLK; |
| 53 | auto FcntlLockOpW = m_isAshmem ? F_SETLKW : F_OFD_SETLKW; |
| 54 | if (unLockFirstIfNeeded) { |
| 55 | // try lock |
| 56 | auto ret = fcntl(m_fd, FcntlLockOp, &m_lockInfo); |
| 57 | if (ret == 0) { |
| 58 | return true; |
| 59 | } |
| 60 | // lets be gentleman: unlock my shared-lock to prevent deadlock |
| 61 | auto type = m_lockInfo.l_type; |
| 62 | m_lockInfo.l_type = F_UNLCK; |
| 63 | ret = fcntl(m_fd, FcntlLockOp, &m_lockInfo); |
| 64 | if (ret != 0) { |
| 65 | MMKVError("fail to try unlock first fd=%d, ret=%d, error:%s", m_fd, ret, strerror(errno)); |
| 66 | } |
| 67 | m_lockInfo.l_type = type; |
| 68 | } |
| 69 | |
| 70 | int cmd = wait ? FcntlLockOpW : FcntlLockOp; |
| 71 | auto ret = fcntl(m_fd, cmd, &m_lockInfo); |
| 72 | if (ret != 0) { |
| 73 | if (tryAgain) { |
| 74 | *tryAgain = (errno == EAGAIN); |
| 75 | } |
| 76 | if (wait) { |
| 77 | MMKVError("fail to lock fd=%d, ret=%d, error:%s", m_fd, ret, strerror(errno)); |
| 78 | } |
| 79 | // try recover my shared-lock |
| 80 | if (unLockFirstIfNeeded) { |
| 81 | m_lockInfo.l_type = LockType2FlockType(SharedLockType); |
| 82 | ret = fcntl(m_fd, cmd, &m_lockInfo); |
| 83 | if (ret != 0) { |
| 84 | // let's hope this never happen |
| 85 | MMKVError("fail to recover shared-lock fd=%d, ret=%d, error:%s", m_fd, ret, strerror(errno)); |
| 86 | } |
| 87 | } |
| 88 | return false; |
| 89 | } else { |
| 90 | return true; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | bool FileLock::fcntlUnLock(bool unlockToSharedLock) { |
| 95 | m_lockInfo.l_type = static_cast<short>(unlockToSharedLock ? F_RDLCK : F_UNLCK); |
nothing calls this directly
no test coverage detected