def lock(self, blocking=True): """ lock the file :param blocking: If blocking is True, will block there until cup gets the lock. True by default. :return: return False if locking fails :raise Exception: raise cup.err.LockFileError if blocking is False and the lock action failed """ if platforms.is_linux(): flags = 0x1 if FILELOCK_SHARED == self._locktype: flags = FILELOCK_SHARED elif FILELOCK_EXCLUSIVE == self._locktype: flags = FILELOCK_EXCLUSIVE else: raise err.LockFileError('does not support this lock type') if not blocking: flags |= FILELOCK_NONBLOCKING ret = None try: ret = fcntl.flock(self._fhandle, flags) except IOError as error: raise err.LockFileError(error) except Exception as error: raise err.LockFileError(error) return ret elif platforms.is_windows(): win_lockfile(self._fhandle, blocking)
def unlock(self): """unlock the locked file""" if platforms.is_linux(): try: fcntl.flock(self._fhandle, FILELOCK_UNLOCK) except Exception as error: raise err.LockFileError(error) elif platforms.is_windows(): win_unlockfile(self._fhandle)
from cup import platforms __all__ = [ 'LockFile', 'FILELOCK_SHARED', 'FILELOCK_EXCLUSIVE', 'FILELOCK_NONBLOCKING', 'FILELOCK_UNLOCK', 'mk_newnode' ] CANNOT_DEL_PATHLIST = ['/'] if platforms.is_linux() or platforms.is_mac(): import fcntl FILELOCK_EXCLUSIVE = fcntl.LOCK_EX FILELOCK_SHARED = fcntl.LOCK_SH FILELOCK_NONBLOCKING = fcntl.LOCK_NB FILELOCK_UNLOCK = fcntl.LOCK_UN elif platforms.is_windows(): import msvcrt def file_size(fobj): """win file size""" return os.path.getsize(os.path.realpath(fobj.name)) def win_lockfile(fobj, blocking=True): """win lock file""" flags = msvcrt.LK_RLCK if not blocking: flags = msvcrt.LK_NBRLCK msvcrt.locking(fobj.fileno(), flags, file_size(fobj)) def win_unlockfile(fobj): """win unlock file"""