Check and create PID file in a race-free manner

This commit is contained in:
Unrud 2015-12-22 06:55:17 +01:00 committed by Unrud
parent 0a09804821
commit 3a9238f670

View File

@ -99,13 +99,20 @@ def run():
# Fork if Radicale is launched as daemon # Fork if Radicale is launched as daemon
if config.getboolean("server", "daemon"): if config.getboolean("server", "daemon"):
if os.path.exists(config.get("server", "pid")): # Check and create PID file in a race-free manner
raise OSError("PID file exists: %s" % config.get("server", "pid")) if config.get("server", "pid"):
try:
pid_fd = os.open(config.get("server", "pid"),
os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except:
raise OSError("PID file exists: %s" %
config.get("server", "pid"))
pid = os.fork() pid = os.fork()
if pid: if pid:
sys.exit() sys.exit()
elif config.get("server", "pid"): # Write PID
with open(config.get("server", "pid"), "w") as pid_file: if config.get("server", "pid"):
with os.fdopen(pid_fd, "w") as pid_file:
pid_file.write(str(os.getpid())) pid_file.write(str(os.getpid()))
sys.stdout = sys.stderr = open(os.devnull, "w") sys.stdout = sys.stderr = open(os.devnull, "w")