Skip to content

Commit 61f3af0

Browse files
committed
Merge branch 'test/modbus_lwip_issue' into 'master'
modbus: Exit server task gracefully to correctly cleanup lwip internals Closes IDFGH-4432 See merge request espressif/esp-idf!12075
2 parents a196d6d + 898cac0 commit 61f3af0

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

components/freemodbus/tcp_slave/port/port_tcp_slave.c

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ void vMBPortEventClose( void );
6666

6767
/* ----------------------- Static variables ---------------------------------*/
6868
static int xListenSock = -1;
69+
static SemaphoreHandle_t xShutdownSemaphore = NULL;
6970
static MbSlavePortConfig_t xConfig = { 0 };
7071

7172
/* ----------------------- Static functions ---------------------------------*/
@@ -462,6 +463,11 @@ static void vMBTCPPortServerTask(void *pvParameters)
462463
// Wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely
463464
xErr = select(xMaxSd + 1 , &xReadSet , NULL , NULL , NULL);
464465
if ((xErr < 0) && (errno != EINTR)) {
466+
// First check if the task is not flagged for shutdown
467+
if (xListenSock == -1 && xShutdownSemaphore) {
468+
xSemaphoreGive(xShutdownSemaphore);
469+
vTaskDelete(NULL);
470+
}
465471
// error occurred during wait for read
466472
ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "select() errno = %d.", errno);
467473
continue;
@@ -626,8 +632,22 @@ void
626632
vMBTCPPortClose( )
627633
{
628634
// Release resources for the event queue.
635+
636+
// Try to exit the task gracefully, so select could release its internal callbacks
637+
// that were allocated on the stack of the task we're going to delete
638+
xShutdownSemaphore = xSemaphoreCreateBinary();
639+
vTaskResume(xConfig.xMbTcpTaskHandle);
640+
if (xShutdownSemaphore == NULL || // if no semaphore (alloc issues) or couldn't acquire it, just delete the task
641+
xSemaphoreTake(xShutdownSemaphore, 2*pdMS_TO_TICKS(CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND)) != pdTRUE) {
642+
ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Task couldn't exit gracefully within timeout -> abruptly deleting the task");
643+
vTaskDelete(xConfig.xMbTcpTaskHandle);
644+
}
645+
if (xShutdownSemaphore) {
646+
vSemaphoreDelete(xShutdownSemaphore);
647+
xShutdownSemaphore = NULL;
648+
}
649+
629650
vMBPortEventClose( );
630-
vTaskDelete(xConfig.xMbTcpTaskHandle);
631651
}
632652

633653
void

0 commit comments

Comments
 (0)