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