daemonize: fork client before loading context

This commit is contained in:
nemunaire 2017-09-26 19:35:31 +02:00
parent 28d4e507eb
commit 30ec912162
2 changed files with 22 additions and 19 deletions

View File

@ -39,10 +39,14 @@ def requires_version(min=None, max=None):
"but this is nemubot v%s." % (str(max), __version__))
def attach(pid, socketfile):
def attach(pidfile, socketfile):
import socket
import sys
# Read PID from pidfile
with open(pidfile, "r") as f:
pid = int(f.readline())
print("nemubot is launched with PID %d. Attaching to Unix socket at: %s" % (pid, socketfile))
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@ -106,28 +110,13 @@ def attach(pid, socketfile):
return 0
def daemonize(socketfile=None, autoattach=True):
def daemonize(socketfile=None):
"""Detach the running process to run as a daemon
"""
import os
import sys
if socketfile is not None:
try:
pid = os.fork()
if pid > 0:
if autoattach:
import time
os.waitpid(pid, 0)
time.sleep(1)
sys.exit(attach(pid, socketfile))
else:
sys.exit(0)
except OSError as err:
sys.stderr.write("Unable to fork: %s\n" % err)
sys.exit(1)
try:
pid = os.fork()
if pid > 0:

View File

@ -77,6 +77,20 @@ def main():
args.files = [x for x in map(os.path.abspath, args.files)]
args.modules_path = [x for x in map(os.path.abspath, args.modules_path)]
# Prepare the attached client, before setting other stuff
if not args.debug and not args.no_attach and args.socketfile is not None and args.pidfile is not None:
try:
pid = os.fork()
if pid > 0:
import time
os.waitpid(pid, 0)
time.sleep(1)
from nemubot import attach
sys.exit(attach(args.pidfile, args.socketfile))
except OSError as err:
sys.stderr.write("Unable to fork: %s\n" % err)
sys.exit(1)
# Setup logging interface
import logging
logger = logging.getLogger("nemubot")
@ -106,7 +120,7 @@ def main():
pass
else:
from nemubot import attach
sys.exit(attach(pid, args.socketfile))
sys.exit(attach(args.pidfile, args.socketfile))
# Add modules dir paths
modules_paths = list()
@ -175,7 +189,7 @@ def main():
# Daemonize
if not args.debug:
from nemubot import daemonize
daemonize(args.socketfile, not args.no_attach)
daemonize(args.socketfile)
# Signals handling
def sigtermhandler(signum, frame):