Created
October 9, 2010 22:12
-
-
Save thepaul/618664 to your computer and use it in GitHub Desktop.
pidfile context manager
This file contains 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
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