Daemonizing a python programme.

Coy Krill ckrill at qvlinc.com
Fri Mar 23 18:47:42 EST 2001


Timothy Grant wrote:

> Hi all,
>
> I have been investigating daemonizing a python programme, and
> have discovered to bits of code that assist in this endeavour:
> daemonize.py and Daemon.py.
>
> I think that I like Daemon.py's method of doing things, but I
> can't get it to work as it imports a module named delay that I
> can't find anywhere.
>
> Does anyone have any success stories with either of these
> tools?
>
> Thanks
>
> --
> Stand Fast,
>     tjg.
>
> Timothy Grant                         tjg at exceptionalminds.com
> Red Hat Certified Engineer            www.exceptionalminds.com
> Avalon Technology Group, Inc.         <><       (503) 246-3630
> >>>>>>>>>>>>>Linux, because rebooting is *NOT* normal<<<<<<<<<
> >>>>This machine was last rebooted:  65 days 23:52 hours ago<<

I combined ideas from both and rolled this one, that works for me.

#  Daemon Module - basic facilities for becoming a daemon process
#
#  Combines ideas from Steinar Knutsens daemonize.py and
#  Jeff Kunces demonize.py

"""Facilities for Creating Python Daemons"""

import os
import time
import sys

class NullDevice:
    def write(self, s):
        pass

def daemonize():
    if (not os.fork()):
        # get our own session and fixup std[in,out,err]
        os.setsid()
        sys.stdin.close()
        sys.stdout = NullDevice()
        sys.stderr = NullDevice()
        if (not os.fork()):
            # hang around till adopted by init
            ppid = os.getppid()
            while (ppid != 1):
                time.sleep(0.5)
                ppid = os.getppid()
        else:
            # time for child to die
            os._exit(0)
    else:
        # wait for child to die and then bail
        os.wait()
        sys.exit()




More information about the Python-list mailing list