Extract deamonize to a dedicated function that can be called from anywhere

This commit is contained in:
nemunaire 2015-05-16 10:24:08 +02:00
parent 29913bd943
commit 220bc7356e
2 changed files with 40 additions and 29 deletions

View File

@ -38,6 +38,44 @@ def requires_version(min=None, max=None):
"but this is nemubot v%s." % (str(max), __version__))
def daemonize():
"""Detach the running process to run as a daemon
"""
import os
import sys
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Unable to fork: %s\n" % err)
sys.exit(1)
os.setsid()
os.umask(0)
os.chdir('/')
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Unable to fork: %s\n" % err)
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def reload():
"""Reload code of all Python modules used by nemubot
"""

View File

@ -68,35 +68,8 @@ def main():
# Daemonize
if not args.debug:
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Unable to fork: %s" % err)
sys.exit(1)
os.setsid()
os.umask(0)
os.chdir('/')
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write("Unable to fork: %s" % err)
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
from nemubot import daemonize
daemonize()
# Setup loggin interface
import logging