multithreading - Proper way to start thread from python daemon -


i need write simple daemon web interface.

the idea use python-daemon package , run wsgiref.simple_server inside 1 thread.

daemon works fine following code :

import daemon import logging import time import signal import threading  logfilename = '/var/log/testdaemon.log' logger = logging.getlogger("daemonlog") logger.setlevel(logging.info) formatter = logging.formatter(     '%(asctime)s:%(levelname)s:%(message)s',     '%y-%m-%d %h:%m:%s') handler = logging.filehandler(logfilename) handler.setformatter(formatter) logger.addhandler(handler)  def initial_program_setup():     logger.info('daemon started')  def do_main_program():     while true:         time.sleep(1)         logger.info('another second passed')  def program_cleanup(signum, frame):     logger.info('daemon stops')     context.terminate(signum, frame)  def reload_program_config(signum, frame):     logger.info('reloading config')  context = daemon.daemoncontext()  context.signal_map = {     signal.sigterm: program_cleanup,     signal.sighup: 'terminate',     signal.sigusr1: reload_program_config,     }  context.files_preserve = [handler.stream]  initial_program_setup()  context:     do_main_program() 

but if start thread in initial_program_setup() :

def web_gui():     logger.info('weg gui started')  web = threading.thread(target=web_gui) web.setdaemon(true)  def initial_program_setup():     logger.info('daemon started')     web.start() 

then looks daemon exits after thread completes. adding like

while true:     time.sleep(1) 

to web_gui() (to make thread run forever, web server should) makes worse: line web gui started doesn't show in log.

my questions are:

  1. why doesn't work? what's proper way start thread in daemon?
  2. maybe there better way control daemon through web interface? such architecture, think should start new thread each interface page, hard scale.

thanks.

this limitation (discussion thread starts here) of daemon library.

tl;dr: options are:

  • don't use daemon, because unrepairably broken in regard.
  • start thread within "with daemoncontext" block.

long version:

when daemon library switches daemon context, double-fork. means first forks , kills parent process. new fork not have thread, exiting parent process equates killing webgui thread. ultimately, solution problem must start permanent threads in newly created child process. downside of doing in daemon context no longer able propagate potential errors user. ideally you'd double-fork, not exit parent process, set daemon , right before entering main loop make parent process exit. not achievable daemon library or library implementing pep3143 draft.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -