#============================================================================== # This library is free software; you can redistribute it and/or modify it under # the terms of version 2.1 of the GNU Lesser General Public License as # published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================== # Copyright (C) 2008 Oracle, Inc. # Copyright (C) 2008 Zhigang Wang #============================================================================== import os # Exceptions that can be raised by this module class LockError(Exception): pass class LockFile(object): '''Represent a lock that is made on the file system, to prevent concurrent execution of this code. Linux's open(2) manual page says O_EXCL does not work with NFS, but it actually does work if both the NFS client (Linux v2.6.6+) and the server support it. Apparently it is commonly implemented nowadays, so it should be quite safe to use in new systems. Unfortunately there is no easy way to check if it is safe or not. ''' def __init__(self, filename): self.filename=filename self.locked=False def acquire(self): try: os.open(self.filename, os.O_CREAT|os.O_RDWR|os.O_EXCL) self.locked=True except OSError, e: raise LockError('Could not create lock file: %s' % e) def release(self): if self.locked: try: os.unlink(self.filename) self.locked=False except OSError, e: raise LockError('Could not remove lock file: %s' % e) def __del__(self): self.release()