sockets,threads and interupts

Ramchandra Apte maniandram01 at gmail.com
Tue Sep 4 23:43:11 EDT 2012


On Tuesday, 4 September 2012 23:41:13 UTC+5:30, Grant Edwards  wrote:
> On 2012-09-04, MRAB <python at mrabarnett.plus.com> wrote:
> 
> > On 04/09/2012 16:26, loial wrote:
> 
> >> I have threaded python script that uses sockets to monitor network
> 
> >> ports.
> 
> >>
> 
> >> I want to ensure that the socket is closed cleanly in all
> 
> >> circumstances. This includes if the script is killed or interupted in
> 
> >> some other way.
> 
> >>
> 
> >> As I understand it signal only works in the main thread, so how can I
> 
> >> trap interupts in my threaded class and always ensure I close the
> 
> >> socket? Using KeyboardInterupt does not seem to work.
> 
> >>
> 
> > You could wrap it in try...finally. The 'finally' clause is guaranteed
> 
> > to be run, so you can close the sockets there.
> 
> >
> 
> > However, if the script is just killed, then it won't get the chance
> 
> > to tidy up.
> 
> 
> 
> That depends on the signal used to "kill" the thread.
> 
> 
> 
> You can catch SIGTERM and SIGINT and clean up before exiting.
> 
> 
> 
> You can't catch SIGKILL, but sending a SIGKILL isn't considered polite
> 
> unless you've already tried SIGTERM/SIGINT and it didn't work.
> 
> 
> 
> -- 
> 
> Grant Edwards               grant.b.edwards        Yow! Are we on STRIKE yet?
> 
>                                   at               
> 
>                               gmail.com

We could just use a "with" statement. Neater, easier.



More information about the Python-list mailing list