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!')
@imankulov
Copy link

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

try:
    return func(*args, **kwargs)
finally:
    lf.truncate(0)

@imankulov
Copy link

And take a look here. I'm not sure whether it works on FreeBSD though.

@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