3

I'm stuck and need help.

I'm using python-daemon package to daemonize a program. The problem is that I don't know how to start and stop the daemon.

When I run

python myscript.py start

A new process is created. However when I run the stop nothing happens.

# Setting logging configuration
logger = logging.getLogger("MyScript")

logger.setLevel(logging.DEBUG)

formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/tmp/myscript.log")
handler.setFormatter(formatter)
logger.addHandler(handler)

pid = daemon.pidlockfile.TimeoutPIDLockFile("/tmp/myscript.pid", 10)
context = daemon.DaemonContext(
    #working_directory='/var/lib/foo',
    umask=0o002,
    pidfile=pid,
    files_preserve=[handler.stream],
    )

loop = True
def program_cleanup_test():
    logger.info("Stopping loop")
    loop = False

context.signal_map = {
    signal.SIGTERM: program_cleanup_test,
    signal.SIGHUP: 'terminate',
    #signal.SIGUSR1: reload_program_config,
    }

print "Running as a daemon"
with context:
    while loop:
        logger.info("0255")
        time.sleep(5)
jlanza
  • 1,208
  • 3
  • 23
  • 43
  • this may help : http://stackoverflow.com/questions/4705564/python-script-as-linux-service-daemon – joe Jun 27 '13 at 20:40
  • @joe that one is not using python-daemon, it is creating a daemon using system tools. – jlanza Jun 27 '13 at 21:56

1 Answers1

0

Try sending a signal to it. If you send SIGTERM your function program_cleanup_test() will be called. If you send SIGHUP, your daemon will terminate.

This shell command sends signals:

kill [-s signal] PID

So you can run:

kill -s TERM your_daemon_pid

and this should run your program_cleanup_test() function.

I hope this will help.


Also you don't need to use:
python myscript.py start

but just:

python myscript.py

because the start goes to sys.argv[1] and that does not change your script. If you want to know what is sys.argv, here is a good explanation: https://stackoverflow.com/a/4118133/4898487

Community
  • 1
  • 1
skywalker
  • 1,230
  • 14
  • 30