examples/modbus: Fix modbus example to keep running

This commit is contained in:
Alan Carvalho de Assis 2023-12-03 14:15:37 -03:00 committed by Xiang Xiao
parent 6dd9adbb5b
commit 454426547c

@ -123,7 +123,6 @@ struct modbus_state_s
#endif #endif
pthread_t threadid; pthread_t threadid;
pthread_mutex_t lock; pthread_mutex_t lock;
volatile bool quit;
}; };
/**************************************************************************** /****************************************************************************
@ -165,7 +164,7 @@ static inline int modbus_initialize(void)
/* Verify that we are in the stopped state */ /* Verify that we are in the stopped state */
if (g_modbus.threadstate != STOPPED) if (g_modbus.threadstate == RUNNING)
{ {
fprintf(stderr, "modbus_main: " fprintf(stderr, "modbus_main: "
"ERROR: Bad state: %d\n", g_modbus.threadstate); "ERROR: Bad state: %d\n", g_modbus.threadstate);
@ -379,7 +378,7 @@ static inline int modbus_create_pollthread(void)
{ {
int ret; int ret;
if (g_modbus.threadstate == STOPPED) if (g_modbus.threadstate != RUNNING)
{ {
ret = pthread_create(&g_modbus.threadid, NULL, ret = pthread_create(&g_modbus.threadid, NULL,
modbus_pollthread, NULL); modbus_pollthread, NULL);
@ -427,25 +426,26 @@ static void modbus_showusage(FAR const char *progname, int exitcode)
int main(int argc, FAR char *argv[]) int main(int argc, FAR char *argv[])
{ {
bool quit = true;
int option; int option;
int ret; int ret;
/* Handle command line arguments */ /* Handle command line arguments */
g_modbus.quit = false;
while ((option = getopt(argc, argv, "desqh")) != ERROR) while ((option = getopt(argc, argv, "desqh")) != ERROR)
{ {
switch (option) switch (option)
{ {
case 'd': /* Disable protocol stack */ case 'd': /* Disable protocol stack */
pthread_mutex_lock(&g_modbus.lock);
g_modbus.threadstate = SHUTDOWN; g_modbus.threadstate = SHUTDOWN;
pthread_mutex_unlock(&g_modbus.lock);
break; break;
case 'e': /* Enable the protocol stack */ case 'e': /* Enable the protocol stack */
{ {
/* Keep running, otherwise the thread will die */
quit = false;
ret = modbus_create_pollthread(); ret = modbus_create_pollthread();
if (ret != OK) if (ret != OK)
{ {
@ -481,7 +481,6 @@ int main(int argc, FAR char *argv[])
break; break;
case 'q': /* Quit application */ case 'q': /* Quit application */
g_modbus.quit = true;
pthread_kill(g_modbus.threadid, 9); pthread_kill(g_modbus.threadid, 9);
break; break;
@ -497,6 +496,13 @@ int main(int argc, FAR char *argv[])
} }
} }
/* Don't exit until the thread finishes */
if (!quit)
{
pthread_join(g_modbus.threadid, NULL);
}
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }