Skip to content

Instantly share code, notes, and snippets.

@artyom
Created September 11, 2012 20:46
Show Gist options
  • Save artyom/3701902 to your computer and use it in GitHub Desktop.
Save artyom/3701902 to your computer and use it in GitHub Desktop.
freebsd/linux pidfile+lockfile
#!/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!')
@artyom
Copy link
Author

artyom commented Sep 12, 2012

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