def use_lock(func, lockfile):
if not os.path.exists(lockfile):
with open(lockfile, 'w') as f:
f.write(str(os.getpid()))
func()
os.remove(lockfile)
return True
else:
return None
To execute a function main() using a lock file "/var/run/myprogram.pid" just write:
use_lock(main, '/var/run/myprogram.pid')
Hope you find it useful.
Since the check and lock part of the code is not atomic, I think there's a very small chance that if you run two programs, both might end up starting. Is there a way to create a lock atomically?
ReplyDeleteHmm, just came across this - http://stackoverflow.com/questions/489861/locking-a-file-in-python