I am reading this Python book that shows a couple of scripts to create my own daemon. When I run the code it does absolutely nothing however.
#! /usr/bin/env python
import sys, os
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
#perform first fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0) #Exit first parent
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
#Decouple from the parent environment
os.chdir("/")
os.umask(0)
os.setsid()
#Perform second fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0) #Exit second parent
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
#The process is now daemonized, redirect standard file descriptors.
for f in sys.stdout, sys.stderr:f.flush()
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(si.fileno(), sys.stdout.fileno())
os.dup2(si.fileno(), sys.stderr.fileno())
The code above uses this daemonize()
function. The daemonize()
function is in a module called demon_process
. Next, please check-out the code that uses this home-made daemon.
from demon_process import daemonize
import time
import sys
def mod_5_watcher():
start_time = time.time()
end_time = start_time + 20
while time.time() < end_time:
now = time.time()
if int(now) % 5 == 0:
sys.stderr.write('Mod 5 at %s\n' % now)
else:
sys.stdout.write('No mod 5 at %s\n' % now)
time.sleep(1)
if __name__ == "__main__":
daemonize(stdout='/Users/Los3r/Documents/pyMeBaby/demons/stdout.log', stderr='/Users/Los3r/Documents/pyMeBaby/demons/stderr.log')
mod_5_watcher()
According to the book I am reading the script above should print statements to the files specified in the stdout and stderr variables overridden in the daemonize()
function as called in main()
. However, when I call this script, even using the sudo
command, nothing happens. :/
I even try changing the directory the stdout and stderr write to as specified in the daemonize()
function to /tmp/stdout.log
and /tmp/stderr.log
but the script still does not work.
What am I missing?
Thanks for reading this player. :D
Regards,
user_loser