[mod_python] Re: forks, daemons and other beasts

Daniel J. Popowich dpopowich at comcast.net
Mon Feb 13 19:08:54 EST 2006


Daniel Nogradi writes:
> Thanks a lot for the code, I didn't even think about such an
> approach, this would be the best of course.
> 
> > For example, if you have this script, /tmp/foo.py:
> > 
> >     ############################################################
> >     # /tmp/foo.py
> > 
> >     import signal
> >     import time
> > 
> >     # ignore the TERM signal, so if apache kills the child process
> >     # that forked me I won't die.
> >     signal.signal(signal.SIGTERM, signal.SIG_IGN)
> > 
> >     # Your Code Here!
> >     # for this demo we'll sleep, so you have time to stop apache and
> >     # see this is still running
> >     time.sleep(30)
> > 
> >     # some output to prove we ran
> >     print "hello, world"
> > 
> >     #
> >     ############################################################
> > 
> > 
> > Then in your handler:
> > 
> >     os.system('python /tmp/foo.py >& /tmp/foo.log &')
> > 
> > 
> > Daniel Popowich
> > ---------------
> > http://home.comcast.net/~d.popowich/mpservlets/
> 
>
> I'm not sure I understand this. AFAIK both os.spawn* and os.system
> start a brand new process, with the only difference being how
> command line arguments are handled. Or not?

For python on unix, the os.spawn* calls are implemented in python with
underlying calls to os.fork and os.exec*.  You can see the python
source yourself; look in os.py in the standard library.  So, there's
really no difference between the exec* and spawn* calls.

You *could* do what you want with calls to os.fork and os.exec*, but
unless you're a unix systems programmer you will be biting off more
than you can chew.  That is, this simple command line:

  $ python myscript.py > logfile 2> errfile &

which can be easily executed from within python with:

    os.system('python myscript.py > logfile 2> errfile &')

would be MANY tens of lines of code if implemented with fork and exec*
calls; setting up the redirection is particularly tricky.  Take a look
at the implementation of the spawn* calls in os.py, that will give you
an idea, plus realize there is NO redirection of std{in,out,err}
happening in the spawn* code.  It's a non-trivial undertaking.

Unless you want the intellectual exercise (which is more than enough
reason in my book!  :-)), or need minutia control of process
parameters within python, I'd go with the os.system method and trap
signal.SIGTERM in your script.

Cheers,

Daniel Popowich
---------------
http://home.comcast.net/~d.popowich/mpservlets/


More information about the Mod_python mailing list