有时写的程序因为资源等等原因,应该只启动一份。利用指定的文件锁,可以实现这样的功能。
import osimport fcntlimport errnodef lock_file(filename): fd = os.open(filename, os.O_CREAT | os.O_WRONLY, 0666) try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) return True except IOError, e: if e.errno in (errno.EACCES, errno.EAGAIN): return Falseif not lock_file('/tmp/test.lock'): print "another instance is running"lock_file('/tmp/test.lock')
再附上一份per......
阅读全文