Agent: Detect closed socket in SocketsPipe

When a socket is closed, select.select() returns the socket in the
read_list. A closed socket can be detected by attempting to read from
it. If 0 data is read, then the socket is closed.

See below for more details:
> If a socket is in the output readable list, you can be
  as-close-to-certain-as-we-ever-get-in-this-business that a recv on
  that socket will return something.
https://docs.python.org/3/howto/sockets.html#non-blocking-sockets
https://stackoverflow.com/questions/17386487/python-detect-when-a-socket-disconnects-for-any-reason
https://stackoverflow.com/questions/17705239/is-there-a-way-to-detect-that-tcp-socket-has-been-closed-by-the-remote-peer-wit
This commit is contained in:
Mike Salvatore 2022-09-12 16:35:36 -04:00
parent fe954bb659
commit c532cdec72
1 changed files with 6 additions and 1 deletions

View File

@ -30,7 +30,9 @@ class SocketsPipe(Thread):
def _pipe(self):
sockets = [self.source, self.dest]
while True:
socket_closed = False
while not socket_closed:
read_list, _, except_list = select.select(sockets, [], sockets, self.timeout)
if except_list:
raise OSError("select() failed on sockets {except_list}")
@ -43,6 +45,9 @@ class SocketsPipe(Thread):
data = r.recv(READ_BUFFER_SIZE)
if data:
other.sendall(data)
else:
socket_closed = True
break
def run(self):
try: