Skip to content

Instantly share code, notes, and snippets.

@thepaul
Created October 9, 2010 22:12
Show Gist options
  • Save thepaul/618664 to your computer and use it in GitHub Desktop.
Save thepaul/618664 to your computer and use it in GitHub Desktop.
pidfile context manager
import os
import contextmanager
@contextlib.contextmanager
def have_pidfile(fname):
f = open(fname, 'w')
f.write('%d\n' % os.getpid())
f.flush()
s = os.fstat(f.fileno())
dev, ino = s.st_dev, s.st_ino
try:
yield f
finally:
try:
# make sure we still own the thing linked there
s = os.stat(fname)
if s.st_dev == dev and s.st_ino == ino:
# (race condition here)
os.unlink(fname)
except OSError:
pass
finally:
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment