I am puzzled by the socketserver module behaviour upon exit, especially regarding unix socket creation and cleanup.
From the code below, and the documentation, i wonder if not removing the unix socket is the normal behaviour, or if i missed something and my program flow prevents the cleanup from happening.
Here is my simple code using python 3.9.2 :
import os
from socketserver import ThreadingUnixStreamServer, StreamRequestHandler
class MyStreamRequestHandler(StreamRequestHandler):
def handle(self):
# dummy action
for raw_line in self.rfile:
print(raw_line)
SOCK = '/tmp/foo.sock'
server = ThreadingUnixStreamServer(SOCK, MyStreamRequestHandler)
try:
# edit: using a "with server:" results in the same behaviour
server.serve_forever()
except KeyboardInterrupt:
print("Interrupted by user")
finally:
# here i see that the socket is still present
os.system(f"ls -l {SOCK}")
# so i remove it manually because i would get an
# 'OSError: [Errno 98] Address already in use'
# on the next script run
try:
os.remove(SOCK)
except FileNotFoundError as e:
pass
I expected that the server would cleanup the socket it created, upon exit or interruption.