7

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()
CS Gamer
  • 225
  • 1
  • 3
  • 12

2 Answers2

10

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().

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I import os, but when trying 'os._exit()' I get the error: Traceback (most recent call last): File "server.py", line 35, in clientThread os._exit(); NameError: global name 'os' is not defined – CS Gamer Nov 28 '12 at 19:07
  • 1
    @CSGamer: Where did you add the import? Are you sure you don't have a typo? Because there's no reason that shouldn't work. – abarnert Nov 28 '12 at 19:13
  • Here are my imports at the top: `import os import sys from thread import *` – CS Gamer Nov 28 '12 at 19:18
  • Also, after sending the interrupt to main, there is no keyboard interrupt received after `interrupt_main()` The weird thing is I only receive the keyboard interrupt after trying to reconnect to the server... – CS Gamer Nov 28 '12 at 19:21
  • @CSGamer: I think with your current code, `os._exit()` is the only feasible alternative. However, I have no idea what's happening to your imports. – NPE Nov 28 '12 at 19:24
  • I realized why os._exit() wasn't working. I didn't have any parameter... Now using 1, it works properly! Thanks – CS Gamer Nov 28 '12 at 20:16
-4

You can just raise SystemExit but that seems really harsh. Maybe some means of co-operative threading would work (ie: a queue with a sentinel)

Jon Clements
  • 138,671
  • 33
  • 247
  • 280