July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Jürgen Hermann
You need to fork a daemon process on a Unix or Unix-like system, and this, in turn, requires a certain precise sequence of system calls.
Daemon processes must detach from their controlling terminal and process group. This is not hard, but it does take some care:
import sys, os
def main( ):
""" An example daemon main routine; writes a datestamp to file
/tmp/daemon-log every 10 seconds.
"""
import time
f = open("/tmp/daemon-log", "w")
while 1:
f.write('%s\n' % time.ctime(time.time( )))
f.flush( )
time.sleep(10)
if _ _name_ _ == "_ _main_ _":
# Do the Unix double-fork magic; see Stevens's book "Advanced
# Programming in the UNIX Environment" (Addison-Wesley) for details
try:
pid = os.fork( )
if pid > 0:
# Exit first parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, "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 exiting
print "Daemon PID %d" % pid
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (
e.errno, e.strerror)
sys.exit(1)
# Start the daemon main loop
main( )Forking a daemon on Unix requires a certain specific sequence of
system calls, which is explained in W. Richard
Steven’s seminal book, Advanced Programming in the Unix Environment (Addison-Wesley). We
need to fork
Read now
Unlock full access