@@ -66,6 +66,7 @@ void vMBPortEventClose( void );
66
66
67
67
/* ----------------------- Static variables ---------------------------------*/
68
68
static int xListenSock = -1 ;
69
+ static SemaphoreHandle_t xShutdownSemaphore = NULL ;
69
70
static MbSlavePortConfig_t xConfig = { 0 };
70
71
71
72
/* ----------------------- Static functions ---------------------------------*/
@@ -462,6 +463,11 @@ static void vMBTCPPortServerTask(void *pvParameters)
462
463
// Wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely
463
464
xErr = select (xMaxSd + 1 , & xReadSet , NULL , NULL , NULL );
464
465
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
+ }
465
471
// error occurred during wait for read
466
472
ESP_LOGE (MB_TCP_SLAVE_PORT_TAG , "select() errno = %d." , errno );
467
473
continue ;
@@ -626,8 +632,22 @@ void
626
632
vMBTCPPortClose ( )
627
633
{
628
634
// 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
+
629
650
vMBPortEventClose ( );
630
- vTaskDelete (xConfig .xMbTcpTaskHandle );
631
651
}
632
652
633
653
void
0 commit comments