Clean Exit from Socket/Program

Bryan Olson fakeaddress at nowhere.org
Tue Jul 9 04:31:57 EDT 2002


Larry wrote:
 > Hi:
 >
 > I have a program running where data is being continuously fed into a 
socket
 > connection.  It seems when I exit the program (control c from 
keyboard), I
 > lose a lot of the data that was in the socket buffer.  I know this is the
 > wrong way to shut down...but right now, I know no other way.
 >
 > I am used to VB where when I shut down a program from a form, my unload
 > event triggers and I can clean up.  I am fairly new to python, and I 
am not
 > sure how to trigger a shutdown signal which would then allow my 
program to
 > catch up and clean up before exiting.
 >
 > Can anyone give me some tips on...
 > 1. How to shut down a python program cleanly

Much the same as in VB.  Every module needs to get the shutdown message,
and end it's own task cleanly.

 > 2. How to ensure that my socket buffer is empty before closing.

First, your protocol must coordinate the termination of the sender and
the receiver.

To terminate socket transmission cleanly, each side should do
sock.shutdown(1) which terminates sending, and then read until the
termination of the other's transmission, which you can detect by a
recv() that successfully returns zero bytes.  Then you can close() or
destroy the socket.  Contrary to popular belief, doing a shutdown(0) (of
the receive side) before a close() is unimportant.


--Bryan




More information about the Python-list mailing list