Go to the documentation of this file.00001
00002 import sys, os
00003
00004 '''This module is used to fork the current process into a daemon.
00005
00006 Almost none of this is necessary (or advisable) if your daemon is being started
00007 by inetd. In that case, stdin, stdout and stderr are all set up for you to
00008 refer to the network connection, and the fork()s and session manipulation
00009 should not be done (to avoid confusing inetd). Only the chdir() and umask()
00010 steps remain useful.
00011
00012 References:
00013
00014 UNIX Programming FAQ
00015 1.7 How do I get my program to act like a daemon?
00016 http://www.unixguide.net/unix/programming/1.7.shtml
00017 http://www.faqs.org/faqs/unix-faq/programmer/faq/
00018
00019 Advanced Programming in the Unix Environment
00020 W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7.
00021
00022 $Id: daemonize.py 57 2008-12-22 16:05:53Z wroniasty $
00023 '''
00024
00025 def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
00026
00027 '''This forks the current process into a daemon. The stdin, stdout, and
00028 stderr arguments are file names that will be opened and be used to replace
00029 the standard file descriptors in sys.stdin, sys.stdout, and sys.stderr.
00030 These arguments are optional and default to /dev/null. Note that stderr is
00031 opened unbuffered, so if it shares a file with stdout then interleaved
00032 output may not appear in the order that you expect. '''
00033
00034
00035 try:
00036 pid = os.fork()
00037 if pid > 0:
00038 sys.exit(0)
00039 except OSError, e:
00040 sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
00041 sys.exit(1)
00042
00043
00044 os.chdir("/")
00045 os.umask(0)
00046 os.setsid()
00047
00048
00049 try:
00050 pid = os.fork()
00051 if pid > 0:
00052 sys.exit(0)
00053 except OSError, e:
00054 sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
00055 sys.exit(1)
00056
00057
00058
00059
00060 si = open(stdin, 'r')
00061 so = open(stdout, 'w')
00062 se = open(stderr, 'w', 0)
00063 os.dup2(si.fileno(), sys.stdin.fileno())
00064 os.dup2(so.fileno(), sys.stdout.fileno())
00065 os.dup2(se.fileno(), sys.stderr.fileno())
00066