Archive for the ‘Python’ Category

Python Daemon Skeleton

Monday, June 23rd, 2008

I was bored, and I’ve been learning Python, so I decided to write a Unix Daemon Skeleton, complete with comments explaining why things are done the way they’re done. It’s attached at the bottom of this entry.

I’ve also been playing around with GUI programming in Python, with wxWidgets, on my MacBook Pro. Hopefully that will turn up something useful; I’ve been considering writing a project management tool, to simplify some operations.

Python Daemon Skeleton

Python: Tips For Writing Daemons

Saturday, May 3rd, 2008

Here’s some useful information for writing daemons in Python.

One common problem that people run into is os.fork() producing zombie processes when children quit. This can easily be overcome by setting the SIGCHLD signal to SIG_IGN. ie:

import signal

signal.signal(signal.SIGCHLD, signal.SIG_IGN)

On some flavors of Unix, you are forced to do a double-fork on startup, in order to go into daemon mode. This is because single forking isn’t guaranteed to detach from the controlling terminal. The solution is this:

import os, sys, time

# Main loop
def main():
    # Drop privs.
    os.setgid(1000) # Replace with desired GID
    os.setuid(1000) # Replace with desired UID

    time.sleep(10)
    sys.exit(0)

if (not os.fork()):
    os.setsid() # Become session leader
    pid = os.fork()

    if (pid):
        # Parent, write PID file
        fp = open('/var/run/my-daemon.pid', 'w')
        fp.write(str(pid))
        fp.flush()

        # Forcibly sync disk
        os.fsync(fp.fileno())
        fp.close()

        os._exit(0)
    else:
        # Child, call main
        main()
else:
    # Parent
    os._exit(0)