import sys
2 import time
3 import fcntl
4
5 class FLOCK(object):
6
7 def __init__(self, name):
8 self.fobj = open(name, 'w')
9 self.fd = self.fobj.fileno()
10
11 def lock(self):
12 try:
13 fcntl.lockf(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) # 给文件加锁,使用了fcntl.LOCK_NB
14 print '给文件加锁,稍等 ... ...'
15 time.sleep(20)
16 return True
17 except:
18 print '文件加锁,无法执行,请稍后运行。'
19 return False
20
21
22 def unlock(self):
23 self.fobj.close()
24 print '已解锁'
25
26 if __name__ == "__main__":
27 print sys.argv[1]
28 locker = FLOCK(sys.argv[1])
29 a = locker.lock()
30 if a:
31 print '文件已加锁'
32 else:
33 print '无法执行,程序已锁定,请稍等'