Socket woes and signals

Donn Cave donn at u.washington.edu
Mon Feb 5 12:36:50 EST 2001


Quoth Craig Findlay <craigf at ilid.com.au>:
| I am writing a simple socket server on an OpenBSD machine, and I would
| like to program the following functionality:
|
| If I send the server a SIGTERM signal, I want it to break out of the
| loop that it is in, and close gracefully. 
|
| The loop is basically the standard:
|
| while 1:
|         conn, addr = s.accept() 
|         data = conn.recv(bufsize)
|         if not data: break
|         do something with data
| conn.close()
|
| Q. This is fine if the client closes the connection, but how do I
| break out of the look in response to say a signal?
|
| If I force the loop to end ungracefully, the socket is left hanging
| and I have to reboot the machine to free it up. But the code normally
| stops at the accept line until a connection is accepted, so how do I
| close the socket properly in that state?

I think you're in a worse pickle than you realize.  It's easy to
interrupt accept() with a signal, you just need a signal handler
(see documentation for the signal module) and an exception handler
(after the signal, accept() will raise an EINTR, at least it does
on NetBSD 1.5.)

But in any event, when the process that bound the socket exits, with
any luck the bound port should close and you won't need to reboot
the computer.  When it gets like that, you probably aren't going to 
solve everything with a SIGTERM anyway.  It couldn't hurt to turn
on the SOL_SOCKET attribute SO_REUSEADDR (see setsockopt.)

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list