54 lines
1.2 KiB
Python
54 lines
1.2 KiB
Python
#!/usr/bin/env python2
|
|
|
|
import os
|
|
import time
|
|
import sys
|
|
import subprocess
|
|
|
|
|
|
def doublefork(pidfile, logfile):
|
|
"""Create a daemon process by double-forking, detaching standard streams and creating a pidfile."""
|
|
def panic(message):
|
|
f = open(logfile, "aw")
|
|
f.write("panic: %s\n" % message)
|
|
f.close()
|
|
|
|
try:
|
|
pid = os.fork()
|
|
except OSError as e:
|
|
panic("%s [%d]" % (e.strerror, e.errno))
|
|
return False
|
|
|
|
if pid == 0:
|
|
# we are the first child
|
|
os.setsid()
|
|
try:
|
|
pid = os.fork()
|
|
except OSError as e:
|
|
panic("%s [%d]" % (e.strerror, e.errno))
|
|
return False
|
|
|
|
if pid == 0:
|
|
# we are the second child
|
|
os.chdir("/")
|
|
os.umask(0)
|
|
else:
|
|
os._exit(0)
|
|
|
|
else:
|
|
os._exit(0)
|
|
|
|
pid = open(pidfile, "w")
|
|
pid.write("%i" % os.getpid())
|
|
pid.close()
|
|
|
|
stdout = os.open(logfile, os.O_CREAT | os.O_WRONLY | os.O_APPEND)
|
|
os.dup2(stdout, sys.stdout.fileno())
|
|
os.dup2(stdout, sys.stderr.fileno())
|
|
return True
|
|
|
|
doublefork("/tmp/pid", "/tmp/log")
|
|
while True:
|
|
time.sleep(2)
|
|
print "cocks"
|