If no pidfile is specified, use a random tmp file.

This commit is contained in:
Paul J. Davis 2010-05-11 23:10:52 -04:00
parent d2561ae681
commit db5bd53c4e

View File

@ -11,9 +11,14 @@ import tempfile
class Pidfile(object):
def __init__(self, path):
self.path = path
"""\
Manage a PID file. If a specific name is provided
it and '"%s.oldpid" % name' will be used. Otherwise
we create a temp file using os.mkstemp.
"""
def __init__(self, fname):
self.fname = fname
self.pid = None
def create(self, pid):
@ -22,14 +27,17 @@ class Pidfile(object):
if oldpid == os.getpid():
return
raise RuntimeError("Already running on PID %s " \
"(or pid file '%s' is stale)" % (os.getpid(), self.path))
"(or pid file '%s' is stale)" % (os.getpid(), self.fname))
self.pid = pid
# write pidfile
fd, fname = tempfile.mkstemp(dir=os.path.dirname(self.path))
# Write pidfile
fd, fname = tempfile.mkstemp()
os.write(fd, "%s\n" % self.pid)
os.rename(fname, self.path)
if self.fname:
os.rename(fname, self.fname)
else:
self.fname = fname
os.close(fd)
def rename(self, path):
@ -50,11 +58,14 @@ class Pidfile(object):
def validate(self):
""" Validate pidfile and make it stale if needed"""
if not self.fname:
return
try:
with open(self.path, "r") as f:
with open(self.fname, "r") as f:
wpid = int(f.read() or 0)
if wpid <= 0: return None
if wpid <= 0:
return
try:
os.kill(wpid, 0)
@ -66,4 +77,4 @@ class Pidfile(object):
except IOError, e:
if e[0] == errno.ENOENT:
return
raise
raise