Randall Hopper wrote:

>
> IIRC "UNIX Network Programming" by Stevens (among others) has some code to
> handle this with an explanation into what each fragment does, described
> under starting daemon processes.  Vaguely I recall double fork, close all
> your open file descriptors, and sometimes become a process group leader,
> and separate yourself from the controlling terminal.

Daemon, double fork magic in Python:

from socket import *
from time import time, ctime, sleep
from threading import Lock, Thread, Event
import os, sys, asyncore, getopt

def main():
    hostname = 'foobar'

    SERVERIP = gethostbyname( hostname )
    HBPORT = 1667
    LISTEN_PORT = 2667
    BEATWAIT = 10

    hbThread = TaskThread (SERVERIP, HBPORT)
    hbThread.start ()

    print "Listening ..."
    listenServer = Listener(LISTEN_PORT)
    while 1:
        asyncore.poll()
        sleep(0.1)

# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent, print eventual PID before
            print "Daemon PID %d" % pid
            sys.exit(0)
    except OSError, e:
        print "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # start the daemon main loop
    main()


--
----------------------------------------------------------------------
Mark A. Bolstad                                 [EMAIL PROTECTED]
Raytheon Systems Company                        (410)278-9149
Scientific Visualization Specialist
U.S. Army Research Laboratory   -   HPC Major Shared Resource Center
----------------------------------------------------------------------


Reply via email to