Page 1 of 1

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

Posted: Mon Oct 28, 2024 2:09 pm
by liyafe1997
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!

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

Posted: Mon Oct 28, 2024 8:59 pm
by MicroController
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.

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

Posted: Tue Oct 29, 2024 8:05 am
by liyafe1997
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.