#!/usr/bin/env python # # Copyright (C) 2009 Zhigang Wang # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program 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 General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see . import os class LockError(Exception): """Exceptions that can be raised by this module. """ 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()