daemon dies on xterm kill

John Hunter jdhunter at nitace.bsd.uchicago.edu
Wed May 29 19:35:48 EDT 2002


I am trying to write an xmlrpc server daemon.  When I 'exit' the xterm
that I launch the daemon in, the exit never completes and I still get
output from the server about connection attempts, though I lose my
prompt.  This occurs whether I launch the program w/ or w/o nohup in
the background.  I am trying to launch it as a regular user, not
root.  Is there something wrong with my daemon code or the way I am
launching it:

--- server code ---
#!/usr/local/bin/python
import sys, os, time, string
import SimpleXMLRPCServer


class MyServe:
    def fetch(self, url):
        return os.popen('lynx -dump %s' % url).read()



pidfile = '/home/jdhunter/.servers/my.pid'
port = 5432
def exit():
    sys.exit(0)
    
def get_daemon_pid():
    if os.path.exists(pidfile):
        pid = open(pidfile, 'r').read()
        return int(pid)
    else:
        return None

def startd():
    print 'Starting daemon...',
    pid = get_daemon_pid()
    if pid:
        print 'Daemon appears to be already running with pid %d' % pid
        exit()
        
    if os.fork()==0:
        os.setsid()
        pid = os.getpid()
        open(pidfile, 'w').write('%s\n' % pid)
        sys.stdout=open("/dev/null", 'w')
        sys.stdin=open("/dev/null", 'r')
        try:
            while(1):
                # Daemon's main code goes here                
                server = SimpleXMLRPCServer.SimpleXMLRPCServer(("mother", port))
                server.register_instance(MyServe())
                server.serve_forever()
        except:
            print 'Caught an exception trying to start the server; cleaning up'
            os.remove(pidfile)
    print 'OK'
    exit()

def stopd():
    print 'Stopping daemon...',
    if not os.path.exists(pidfile):
        print 'Daemon does not appear to be running'
        return
    pid = get_daemon_pid()
    os.popen('kill -9 %d' % pid)
    print 'OK'
    os.remove(pidfile)

def usage():
    print 'Usage %s start|stop|restart' % sys.argv[0]
    exit()


if len(sys.argv) != 2:
    usage()

if sys.argv[1]=='start':
    startd()
elif sys.argv[1]=='stop':
    stopd()
elif sys.argv[1]=='restart':
    stopd()
    time.sleep(1)
    startd()

else:
    usage()



More information about the Python-list mailing list