I noticed that each time I create a new socket, the fd in it will grow. Will it cause problem with the fd resource being exhausted?
Below is a sample test code: when the TCP connection was not successful, I saw in the exception that sock.fd has been set to -1. I don’t know the following sock.close () will correctly release all resources or not, but in the next loop, a new socket will have a higher number in its fd. I saw this code running with fd value growing up to 1024. and I did not follow up after that. My concern is, will this eventually exhaust fd or the fd number will “wrap around”?
import errno
import network
import time
import usocket as socket
def dbg_print(msg, line_end=None):
if line_end is None:
print(msg)
else:
print(msg, end=line_end)
if __name__ == "__main__":
count = 0
conn = network.Cellular()
dbg_print(f"Unit test Waiting for cellular connectivity...", line_end='')
# We give time to connect before giving up. TWe give iup to 5 minutes
while not conn.isconnected() and count < 300:
time.sleep(1)
count += 1
dbg_print(".", line_end='')
if conn.isconnected():
dbg_print("CONNECTED!")
ret_value = True
else:
dbg_print("FAILED TO CONNECT!")
n_file = 0
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
dbg_print(f"socket created {sock}")
sock.connect(("www.google.com", 20000))
except OSError as ex:
if ex.errno == errno.ENFILE:
n_file += 1
if n_file % 800 == 1:
dbg_print(f"ENFile = {n_file}")
else:
dbg_print(f" {sock} connect err = {ex} ")
sock.close()
time.sleep_ms(10)
continue
dbg_print(f"connection established {sock}")
sock.close()
time.sleep_ms(500)