def daemonize(stdin='<STR_LIT>', stdout='<STR_LIT>', stderr='<STR_LIT>'):
<EOL>try:<EOL><INDENT>pid = os.fork()<EOL>if pid > <NUM_LIT:0>:<EOL><INDENT>os.waitpid(pid, <NUM_LIT:0>)<EOL>return <NUM_LIT:0>  <EOL><DEDENT><DEDENT>except OSError as e:<EOL><INDENT>sys.stderr.write("<STR_LIT>" % (e.errno, e.strerror))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>os.chdir("<STR_LIT:/>")<EOL>os.umask(<NUM_LIT:0>)<EOL>os.setsid()<EOL>try:<EOL><INDENT>pid = os.fork()<EOL>if pid > <NUM_LIT:0>:<EOL><INDENT>sys.exit(<NUM_LIT:0>)  <EOL><DEDENT><DEDENT>except OSError as e:<EOL><INDENT>sys.stderr.write("<STR_LIT>" % (e.errno, e.strerror))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>si = open(stdin, '<STR_LIT:rb>')<EOL>so = open(stdout, '<STR_LIT>')<EOL>se = open(stderr, '<STR_LIT>', <NUM_LIT:0>)<EOL>os.dup2(si.fileno(), sys.stdin.fileno())<EOL>os.dup2(so.fileno(), sys.stdout.fileno())<EOL>os.dup2(se.fileno(), sys.stderr.fileno())<EOL>return <NUM_LIT:1><EOL>
Double fork-trick. For starting a posix daemon.

This forks the current process into a daemon. The stdin, stdout, and stderr
arguments are file names that will be opened and be used to replace the
standard file descriptors in sys.stdin, sys.stdout, and sys.stderr. These
arguments are optional and default to /dev/null. Note that stderr is opened
unbuffered, so if it shares a file with stdout then interleaved output may
not appear in the order that you expect.

Thanks to:
http://code.activestate.com/recipes/66012-fork-a-daemon-process-on-unix/