run detached

Sean Blakey sblakey at freei.com
Fri Apr 28 01:03:24 CEST 2000


Michael Ströder wrote:
> 
> HI!
> 
> How can I automatically detach from console after starting up with
> SocketServer? (E.g. web server with access and error logging to
> files.)
> 
> Ciao, Michael.
> --
> http://www.python.org/mailman/listinfo/python-list
I think what you want is a daemon process (I assume you are looking for
the Unix answer since you are posting from a linux email client).

Starting a daemon requires the same steps in any language:
1. Fork from the parent tty.
2. Exit the parent process (all further steps occur in the child
process).
3. Call setsid() to put your child process in a new process group.
4. Redirect stdin, stdout, and stderr to /dev/null (or a file of your
choice)
5. chdir to / (not strictly necessarry, but polite).
In python , it looks like this (assuming main() is your code):

import os
import sys
if os.fork():
	sys.exit(0)	# In parent process
else:
	os.setsid()
	sys.stdin = open('/dev/null')
	sys.stdout = open('/dev/null', 'w')
	sys.stderr = open('/dev/null', 'w')
	os.chdir('/')
	main()

I have been playing with creating an object wrapper for daemon
processes, and this may be useful to you (it's still pretty raw).  If
you want, you can check it out at http://members.home.com/seanb/python/
-- 
Sean Blakey
FreeInternet.com
sblakey at freei.com
(253)796-6500x1025




More information about the Python-list mailing list