Socket.close() does not stop any blocking socket.accept() calls that are already running on that socket.
I have several threads in my python program that only run a blocking socket.accept() call on a unix domain socket that has been closed already. I want to kill these threads by making the socket.accept() calls stop or raise an exception.
I am trying to do this by loading new code in the program, without stopping the program. Therefore, changing the code that spawned these threads or that closed the sockets is not an option.
Is there any way to do this?
This is similar to https://stackoverflow.com/a/10090348/3084431, but these solutions wont work for my code:
- This point is not true, closing won't raise an exception on the accept. shutdown does, but that can not be called anymore when the thread is closed.
- I can not connect to this socket anymore. The socket is closed.
- The threads with the accept calls are already running, I can't change them.
- Same as 3
For clarification, I have written some example code that has this problem. This code works in both python 2 and python 3.
import socket
import threading
import time
address = "./socket.sock"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(address)
sock.listen(5)
def accept():
print(sock.accept())
t = threading.Thread(target=accept, name="acceptorthread")
t.start()
sock.close()
time.sleep(0.5) # give the thread some time to register the closing
print(threading.enumerate()) # the acceptorthread will still be running
What I need is something that I can run after this code has finished that can stop the acceptor thread somehow.