Why are the methods sys.exit(), exit(), raise SystemExit not working?

CS Gamer picture CS Gamer · Nov 28, 2012 · Viewed 11.5k times · Source

I need an alternative to kill the python script while inside a thread function. My intention is killing the server when the client enters a 0... Is this not working because the threads haven't been terminated? Here is my code:

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
print 'Socket created'

try:
    socket.bind((HOST, PORT))
except socket.error, message:
    print 'Bind statement failed. ERROR: ' + str(message[0]) + ' Message: ' +    message[1]
    sys.exit()

print 'Socket Binding Successful'

socket.listen(10)
print 'Socket is currently listening'


def clientThread(connection):
    while 1:
        data = connect.recv(1024)
        try:
            quit = int(data)
        except:
            quit = 3
        if quit == 0:
            print 'Closing the connection and socket...'
            connect.close()
            socket.close()
            sys.exit(); //Alternative needed here...
            break
        reply = 'Ok....' + data
        if not data:
            break
        connect.sendall(reply)


while 1: #forever loop
    connect, address = socket.accept()
    print 'Just connected with ' + address[0] + ' : ' + str(address[1])
    start_new_thread(clientThread, (connect,))

socket.close()

Answer

NPE picture NPE · Nov 28, 2012

The problem is that all sys.exit() does is raise SystemExit. Since this happens in a worker thread, the effect is to stop that thread (exceptions don't propagate across threads).

You could trying signalling to the main thread that the script needs to terminate, either though some mechanism of your own, or by calling thread.interrupt_main().

For a sledgehammer approach, call os._exit().