[Python-au] running a socket server as deamon

Daryl Tester dt-pythonau at handcraftedcomputers.com.au
Fri Feb 12 11:56:59 UTC 2010

James Alford wrote:

> Just need some advice on the best approach to running a socket server
> that I have.  The socket server sits on a vps at a host, vps is
> running centos5.2.  I need to ensure that this socket server is always
> running.

First up, does the server have a history of breaking?  If you're using
the Python library's SocketServer a few well placed exception handlers
should stop the rug being pulled out from under it.

> I'm still investigating whether the vps does kill the the
> server process in its clean up.

That depends on what mechanism has been used to start it (although few
processes survive a server reboot - I presume you're more worried here
about the process being terminated cleanly).  If you use the rc.d style
of "service management", these can be used to start and stop the script
at system startup and shutdown.  Alternatively spawning it out of inittab
(if Centos is still running the old style init), although you'd have to
check on what (if any) the style of process termination is used when the
system is being shut down.

> The couple of ideas I have are:
> * Running the socket server as a deamon.
> * Create a monitor process that checks to see if the pid of the socket
> server exists, then if it can connect to the socket port, calls a
> restart on the daemon and exits.
> * Run the monitor process from a cron job.

Urk - as a Unix admin, the last option has always struck me as very unclean.
If you don't want to write the program as a parent monitoring child process
type arrangement, use something like daemontools to start and manage the
process.  If the program has been written so that it doesn't fork and attempt
to background itself, if/when it does terminate daemontools will restart the
program *immediately* (well, as fast as a wait() call returns, which will be
millisecond type timing).  With the cron option, if the monitor job is
executing every minute you're going to have up to a 60 second delay before
the process is restarted.

What I like about the daemontools method is that you don't have to particularly
worry about writing a daemon style program, and if you write to standard out/
standard error you can get logfile management thrown in as an added bonus.  

I've written several production systems using this method (although only one
using SocketServer - I tend to roll my own server framework) and for me it's
worked a treat (not for all cases, but certainly most of 'em).

  Daryl Tester

"Every time a marketeer uses the phrase 'light-year' as a unit of time,
 God kills an astrophysicist."

More information about the python-au mailing list