
import time
import os
import sys

def run():
    while True:
        print '1time'
        time.sleep(1)

def daemon():
    try:
        pid = os.fork()
        if pid > 0:
           sys.exit(0)
    except OSError, e:
        print 'fork #1 fail', e
        sys.exit(1)
    os.chdir('/')
    os.setsid()
    os.umask(0)
    try:
        pid = os.fork()
        if pid > 0:
           print 'daemon pid %d' % pid
           sys.exit(0)
    except OSError, e:
        print 'fork #2 fail', e
        sys.exit(1)
    nulldev = '/dev/null'
    stdin = file(nulldev, 'r')
    stdout = file('/tmp/stdout', 'a+', 0)
    stderr = file(nulldev, 'a+', 0)
    os.dup2(stdin.fileno(), sys.stdin.fileno())
    os.dup2(stdout.fileno(), sys.stdout.fileno())
    os.dup2(stderr.fileno(), sys.stderr.fileno())
    return pid

if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == '-d':
        daemon()
    run()

@@ -26,16 +26,520 @@
 port sys
+%0Aimport atexit%0Aimport os %0Aimport signal%0A%0Adef writeData(signum, fram):%0A    with open('/tmp/data','a+') as fd:%0A        fd.write('asdfasa%5Cn')%0A%0A%0Adef term(signum, fram):%0A    #sys.exitfunc()%0A    raise SystemExit(%0A            u%22Terminating on signal %25(signum)r%22%0A                %25 vars())%0A%0Adef writepid(name,pid):%0A    pidpath = os.path.join('/tmp','%25s.pid'%25name)%0A    with open(pidpath,'w') as fd:%0A        fd.write(str(pid))%0A%0Adef delpid(name):%0A    pidpath = os.path.join('/tmp',name+'.pid')%0A    os.remove(pidpath)
 %0A%0Adef ru
@@ -615,16 +615,20 @@
  daemon(
+name
 ):%0A    t
@@ -807,16 +807,52 @@
 etsid()%0A
+    os.setgid(99)%0A    os.setuid(99)%0A
     os.u
@@ -904,32 +904,62 @@
     if pid %3E 0:%0A
+           writepid(name,pid)%0A
            print
@@ -1158,21 +1158,15 @@
 ile(
-'/tmp/stdout'
+nulldev
 , 'a
@@ -1302,32 +1302,33 @@
 t.fileno())%0A    
+#
 os.dup2(stderr.f
@@ -1353,24 +1353,146 @@
 r.fileno())%0A
+    atexit.register(delpid,name=name)%0A    signal.signal(signal.SIGHUP, writeData)%0A    signal.signal(signal.SIGTERM, term)%0A
     return p
@@ -1573,16 +1573,16 @@
 = '-d':%0A
-
         
@@ -1588,16 +1588,32 @@
  daemon(
+'example-daemon'
 )%0A    ru

add more detail about pid file create and destore