#!/usr/bin/env python # PyDaemonize is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # PyDaemonize is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with PyDaemonize. If not, see . import os def daemonize(log_folder, wd="/", umask=0): try: f = os.fork() except OSError as e: print("SEVERE: Error forking.. <{fork}>".format(fork=e)) print("SEVERE: Trace -> {trace}".format( trace=traceback.format_exc())) raise e from None if f != 0: sys.exit(0) else: signal.signal(signal.SIGHUP, lambda x, y: print("SIGHUP received during process forking, ignoring signal")) os.chdir(wd) os.setsid() os.umask(umask) try: f = os.fork() except OSError as e: print("SEVERE: Error forking.. <{fork}>".format(fork=e)) print("SEVERE: Trace -> {trace}".format( trace=traceback.format_exc())) raise e from None if f != 0: sys.exit(0) print("INFO: Started as Daemon") r = open("/dev/null", "r") os.dup2(r.fileno(), 0) buffering = 1 # line buffering w = open(log_folder, "w", buffering=buffering) os.dup2(w.fileno(), 1) os.dup2(w.fileno(), 2)