Question

I want to create a program that runs forever, which there is only one instance running at a time and that can be launched with an init.d script. python-daemon seems to be a good choice to do that as it is the reference implementation of PEP 3143.

Anyway I can't understand what the PID lock file is for, since it doesn't prevent the program to be run twice.

Should I manually check for the existence of the lock file in my init.d script (based on '/etc/init.d/skeleton') ? Also how am I supposed to kill it ? Get the PID number in the PID file and send a SIGTERM ?

Thanks a lot.

Was it helpful?

Solution

I ended up using Sander Marechal's code whose site is currently down so here's the link to a pastebin : http://pastebin.com/FWBUfry5

Below you can find an example of how you can use it, it produce the behavior I expected : it does not allow you to start two instances.

    import sys, time
    from daemon import Daemon


    class MyDaemon(Daemon):
            def run(self):
                    while True:
                            time.sleep(1)

    if __name__ == "__main__":
            daemon = MyDaemon('/tmp/daemon-example.pid')
            if len(sys.argv) == 2:
                    if 'start' == sys.argv[1]:
                            daemon.start()
                    elif 'stop' == sys.argv[1]:
                            daemon.stop()
                    elif 'restart' == sys.argv[1]:
                            daemon.restart()
                    else:
                            print "Unknown command"
                            sys.exit(2)
                    sys.exit(0)
            else:
                    print "usage: %s start|stop|restart" % sys.argv[0]
                    sys.exit(2)

OTHER TIPS

For me it effectively prevents via the PID file that a second instance is started. Are you using it correctly? My example is based on what I found at the PEP 3143 reference and in the sources:

#!/usr/bin/env python

import daemon, os, time, lockfile

with daemon.DaemonContext(
    pidfile=lockfile.FileLock('./pydaemon.pid'),
    working_directory=os.getcwd()):
  for i in range(10):
    with open('./daemon.log', 'a') as logFile:
      logFile.write('%s %s\n' % (os.getpid(), i))
    time.sleep(1)

If I start that once, it creates the PID lock file. If I start it a second time, the second instance sleeps until the first is finished; normal daemons won't finish, so this effectively blocks the second instance for good. If, however, the first daemon terminates, the second is started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top