#!/usr/bin/env python
#encoding: utf8
import sys, os, time
import fcntl,errno
import struct
class LockException(Exception):
pass
lock_dir = '/tmp'
def lock(lock_name, timeout=0, mode=0600):
def decorator(func):
def wrapper(*args, **kwargs):
old_umask = os.umask(0)
try:
lock_file = os.path.join(lock_dir, '.%s.lck' % lock_name)
lock_fd = os.open(lock_file, os.O_CREAT|os.O_WRONLY, mode)
os.umask(old_umask)
except OSError, e:
os.umask(old_umask)
raise LockException("lock error: %s" % e)
lock_flags = fcntl.LOCK_EX
if timeout is not None:
lock_flags |= fcntl.LOCK_NB
start_time = time.time()
while True:
try:
fcntl.lockf(lock_fd, lock_flags)
break
except IOError, e:
if e.errno == errno.EAGAIN and time.time() < (start_time + timeout):
time.sleep(0.05)
else:
raise LockException("Lock error:%s", e)
try:
return func(*args, **kwargs)
finally:
fcntl.lockf(lock_fd, fcntl.LOCK_UN);
return wrapper
return decorator
@lock("test", timeout=10, mode=0666)
def LockFunc():
print "lockRun..."
if __name__ == "__main__":
LockFunc()