Created
September 11, 2012 20:46
-
-
Save artyom/3701902 to your computer and use it in GitHub Desktop.
freebsd/linux pidfile+lockfile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os, fcntl, time | |
def locked(func): | |
def wrapper(*args, **kwargs): | |
with open('LOCKFILE','a+') as lf: | |
try: | |
fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) | |
except IOError: | |
raise SystemExit('Cannot acquire lock') | |
else: | |
lf.truncate(0) | |
lf.write('%d\n' % os.getpid()) | |
lf.flush() | |
try: | |
func(*args, **kwargs) | |
finally: | |
lf.truncate(0) | |
return wrapper | |
@locked | |
def job(foo): | |
print "Doing serious business" | |
print foo | |
time.sleep(15) | |
print "Bye" | |
if __name__ == "__main__": | |
job('yo, dawg!') |
And take a look here. I'm not sure whether it works on FreeBSD though.
Thank you, I've updated the code with the snippet you suggested.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The wrapper doesn't return what the original function returns and also truncate won't happen if function raises an exception. What about changing lines 16-17 with