import os import signal import configparser from nntp.tiny.config import (ConfigSectionException, ConfigValueException) class Daemon(): def init(config: configparser.ConfigParser): if not config.has_section('daemon'): raise ConfigSectionException('daemon') if not config.has_option('daemon', 'pidfile'): raise ConfigValueException('daemon', 'pidfile') pidfile = config.get('daemon', 'pidfile') pid = os.fork() if pid > 0: exit(0) with open(pidfile, 'w') as fh: print(str(os.getpid()), file=fh) def stop(sig, trace): os.unlink(pidfile) exit(0) signal.signal(signal.SIGTERM, stop)