[python-uk] how to kill the server in program

xtian xtian at babbageclunk.com
Thu Feb 16 11:09:41 CET 2006

On 2/15/06, Yang, W (Wanjuan) <w.yang at dl.ac.uk> wrote:
> Since the server main thread and child thread will run forever, my question is how can I exit the server nicely in the program when it is required (e.g no clients coming for a while) rather than using 'Ctrl-c' or kill the process.
> another question is: Is that when the main thread is killed, then the child thread will stop as well? In this case, before killing the main thread, we have to make sure the child thread already finish its job.  But how the main thread know whether the child thread finish the job or not. in other words, how does the main thread communicate the child thread?

What Chris said about making the child thread a daemon is right.
Another technique I've found useful when writing threaded servers like
this is to use the timeout facility of sockets (in Python 2.3 onwards)
- you can then have the child thread loop accepting connections *or*
timing out, and checking a run flag to determine when you should stop.
Something like (not tested):


class ServerThread(threading.Thread):
    def __init__(self, sock):
        self.run = True
        self.sock = sock

    def please_stop(self):
        self.run = False

    def run(self):
        while self.run:
                conn, address = self.sock.accept()
                # do stuff with connection...
            except socket.timeout:
                pass # maybe track how many consecutive timeouts?
        # any cleanup can go here.

I've found that having the timeout in there makes everything much
easier to handle.


More information about the python-uk mailing list