I’ve recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Python one doesn’t. This is seen when a separate thread is used to spawn the server. Code is as follows:
// Java code
package pkg;
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(final String[] args) throws Exception {
final Thread t = new Server();
t.start();
}
}
class Server extends Thread {
@Override
public void run() {
try {
final ServerSocket sock = new ServerSocket(12345);
while(true) {
final Socket clientSock = sock.accept();
clientSock.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
and Python code:
# Python code
import threading, sys, socket, signal
def startserver():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 12345))
s.listen(1)
while True:
csock, caddr = s.accept()
csock.sendall('Get off my lawn kids...\n')
csock.close()
if __name__ == '__main__':
try:
t = threading.Thread(target=startserver)
t.start()
except:
sys.exit(1)
In both the above code snippets, I create a simple server which listens to TCP requests on the given port. When Ctrl+C is pressed in case of the Java code, the JVM exits whereas in the case of the Python code, all I get is a ^C at the shell. The only way I can stop the server is press Ctrl+Z and then manually kill the process.
So I come up with a plan; why not have a sighandler which listens for Ctrl+Z and quits the application? Cool, so I come up with:
import threading, sys, socket, signal
def startserver():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 12345))
s.listen(1)
while True:
csock, caddr = s.accept()
csock.sendall('Get off my lawn kids...\n')
csock.close()
def ctrlz_handler(*args, **kwargs):
sys.exit(1)
if __name__ == '__main__':
try:
signal.signal(signal.SIGTSTP, ctrlz_handler)
t = threading.Thread(target=startserver)
t.start()
except:
sys.exit(1)
But now, it seems as I’ve made the situation even worse! Now pressing Ctrl+C at the shell emits ‘^C’ and pressing Ctrl+Z at the shell emits ‘^Z’.
So my question is, why this weird behaviour? I’d probably have multiple server processes running as separate threads in the same process so any clean way of killing the server when the process receives SIGINT? BTW using Python 2.6.4 on Ubuntu.
TIA,
sasuke
Several issues:
Don’t catch all exceptions and silently exit. That’s the worst possible thing you can do.
Unless you really know what you’re doing, never catch SIGTSTP. It’s not a signal meant for applications to intercept, and if you’re catching it, chances are you’re doing something wrong.
KeyboardInterrupt is only sent to the initial thread of the program, and never to other threads. This is done for a couple reasons. Generally, you want to deal with ^C in a single place, and not in a random, arbitrary thread that happens to receive the exception. Also, it helps guarantee that, in normal operation, most threads never receive asynchronous exceptions; this is useful since (in all languages, including Java) they’re very hard to deal with reliably.
You’re never going to see the KeyboardInterrupt here, because your main thread exits immediately after starting the secondary thread. There’s no main thread to receive the exception, and it’s simply discarded.
The fix is two-fold: keep the main thread around, so the KeyboardInterrupt has somewhere to go, and only catch KeyboardInterrupt, not all exceptions.