Kill Socket.accept() Call On Closed Unix Socket
Solution 1:
There is no mechanism in kernel to notify every listener that a socket is closed. You have to write something yourself. A simple solution is to use timeout on socket:
sock.settimeout(1)
defaccept():
whileTrue:
try:
print(sock.accept())
except socket.timeout:
continuebreak
Now when you close the socket the next call (after a timeout) to .accept()
will throw a "bad descriptor" exception.
Also remember that sockets api in Python is not thread safe. Wrapping every socket call with a lock (or other synchronization methods) is advised in multi-threaded environment.
More advanced (and efficient) would be to use wrap your socket with a select call. Note that the socket does not have to be in non-blocking mode in order to use it.
Therefore, changing the code that spawned these threads or that closed the sockets is not an option.
If that's the case, then you are doomed. Without changing the code running in threads it is impossible to achieve. It's like asking "how can I fix my broken car without modifying the car". Won't happen, mate.
Solution 2:
You should only call .accept()
on a socket that has given the "readable" result from some selectors
. Then, accept doesn't need to be interrupted.
But in case of spurious wakeup, you should have the listening socket in O_NONBLOCK
mode anyway.
Post a Comment for "Kill Socket.accept() Call On Closed Unix Socket"