0

!!! subprocess didn't work for me.

I want to run python script daemon.py as a daemon. This script needs to be activated from another script called starter.py

Requirements:

  1. starter.py should not wait for daemon.py to finish. This requirement is met by using fork() in starter.py.
import os

pid = os.fork()
if pid == 0:
   os.system("python daemon.py")

This meets the first requirement but still faces a problem, and brings us to the second requirement.

  1. daemon.py should keep running even if I quit starter.py. This requirement is not met by using fork.

I then tried using subprocess as suggested by answers in here Python spawn off a child subprocess, detach, and exit

import subprocess

subprocess.Popen(['python', 'daemon.py'],
                 cwd="/",
                 stdout=None,
                 stderr=None)

This too suffers from the same problem. When I quit starter.py, daemon.py also stops. I'm using SIGTERM event listener on daemon.py. And it is listening to events from starter.py. Hence, the problem.

daemon.py looks like this.

import sys
import signal

def handler():
    other_business()
    sys.exit(0)

while True:
     business()
     signal.signal(signal.SIGTERM, handler)
     try:
         time.sleep(1)
     except KeyboardInterrupt:
         exit()

PYTHON VERSION: 3.5.2

How do I run daemon.py completely independent of starter.py?

Saurav Pathak
  • 796
  • 11
  • 32

0 Answers0