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

Chris Miles miles.chris at gmail.com
Wed Feb 15 11:27:36 CET 2006


On 15 Feb 2006, at 09:42, Yang, W (Wanjuan) 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.

You can define signal handlers to clean things up and exit cleanly if  
a kill signal is sent to the process.  See http://docs.python.org/lib/ 
module-signal.html

> 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?

If you don't want the main thread to block on waiting for child  
threads to die before exiting cleanly, you can mark child threads as  
daemon threads using thread.setDaemon(1). See http://docs.python.org/ 
lib/thread-objects.html

If you don't want your main thread to die before the child threads  
have cleanly finished, then make sure to setDaemon(0) and you may  
also need to signal the child threads that they need to cleanup and  
exit.  A thread-safe method of doing this is to use a threading Event  
object.  Create one object and set it to true when you want all the  
children to exit.  The children need to periodically check the Event  
object and perform any cleanup if they find it set.  See http:// 
docs.python.org/lib/event-objects.html

Cheers,
CM

-- 
Chris Miles
http://chrismiles.info/



More information about the python-uk mailing list