close() does not really release the fd which is created by socket()

liyafe1997
Posts: 2
Joined: Mon Oct 28, 2024 1:35 pm

close() does not really release the fd which is created by socket()

Postby liyafe1997 » Mon Oct 28, 2024 2:09 pm

I use

Code: Select all

socket(addrFamily, SOCK_DGRAM, ipProtocol);
or

Code: Select all

socket(addrFamily, SOCK_STREAM, ipProtocol);
to create UDP/TCP socket, then bind(), then recv()/recvfrom() in a FreeRTOS task, then vTaskDelete(the recv task) and close() it in another FreeRTOS task, whatever it is a TCP or UDP, seems the fd seems never be released after close().

I can see the new fd number for the new socket() still increasing, it can be from 58, 59, 60.... until 64, then no longer can make new socket() (errno 23, reached maximum fd).

Even I just create it and never really use it.

The code looks like

Code: Select all

sock = socket(addrFamily, SOCK_DGRAM, ipProtocol);
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);

int err = bind(sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
recvfrom(sock, rxBuffer, sizeof(rxBuffer) - 1, 0, (struct sockaddr *)&sourceAddr, &socklen);
//--------This task is being blocking since there are no incoming data--------
Then in another task

Code: Select all

vTaskDelete(the above task handler);
close(sock);
IDF version is 5.3.1, chip is ESP32C6.
Is it anything wrong with my code? Do I missed something for close/release the socket?

Thank you!

MicroController
Posts: 1725
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: close() does not really release the fd which is created by socket()

Postby MicroController » Mon Oct 28, 2024 8:59 pm

Do not vTaskDelete() any task other than the current one (vTaskDelete(NULL)).

If you have to, try only closing the socket from the other task, and have the socket-reading task check the value returned from recvfrom() for 0/-1 and then delete itself after releasing any ressources it may hold.

liyafe1997
Posts: 2
Joined: Mon Oct 28, 2024 1:35 pm

Re: close() does not really release the fd which is created by socket()

Postby liyafe1997 » Tue Oct 29, 2024 8:05 am

MicroController wrote:
Mon Oct 28, 2024 8:59 pm
Do not vTaskDelete() any other task than the current one (vTaskDelete(NULL);).

If you have to, try only closing the socket from the other task, and have the socket-reading task check the value returned from recvfrom() for 0/-1 and then delete itself after releasing any ressources it may hold.
Previously the code just like what you said, it doesn't work (fd number seems not be released) then I just add [vTaskDelete(recv task)] have a try but still not solve it.

Who is online

Users browsing this forum: No registered users and 330 guests