简体   繁体   中英

Forcibly terminate a python script

I'm writing an app with a server and client, I want to stop the server when I close the tkinter UI, but the while loop waits for the server.accept() and never terminates, even using sys.exit, it's running threaded btw. I am running a function on gui close, but it doesn't want to terminate.

Here is the example:

while waiting_for_connection: # This is in a threaded function
    conn, addr = server.accept() # It's stuck on this line while waiting for connection
    thread = threading.Thread(target=handle_client, args=(conn, addr)) # Here it connects, but it doesn't reach the end of a loop if no one connects
    thread.start()

Any fix for that?

Any help will be appreciated!

Likely the server is waiting for non-daemon threads to exit, but they aren't because they are still waiting on active sockets. You can set thread.daemon=True to exit the program exit immediately and let the system close the sockets, or you can keep a list of sockets and reset/close them via an exit handler registered via atexit.register .

You can get fancier on exit by letting the socket communications go through some sort of a graceful termination, but that depends on the protocol you are using. As an example, suppose you want server shutdown to wait until all current data is sent. A single SIGTERM could mean to gracefully finish the current tasks at hand then exit. A SIGABRT or perhaps two SIGINTs in a row could mean to reset and get out now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM