Hi I have C Program that starts multiple threads inside the main.cpp and then joins them at the end. Inside the thread functions there are mostly while loops for communication / data transfer (profinet and TCP) I have cleanup handler functions that are called when closing a thread.
I want to use <signal.h> to catch Ctrl+C and exit my program. The only solution that I can think of is doing this in every single thread function.
But is there a smarter way of doing this wihtout the need to catch Ctrl+C in every single thread function that exists? How can I ensure that every cleanup function is called in all threads? When Ctrl+C is catched?
If I use a static volatile sig_atomic_t variable for my while loops inside my void functions that I use for threads and set this variable to 0 with my signal handler function every thread is terminated correctly but it seems that it keeps stuck in the main.cpp loop that looks roughly like this:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
static volatile sig_atomic_t keep_running = 1;
static void sig_handler(int _)
{
(void)_;
keep_running = 0;
}
int main(void)
{
char keystr[2], key;
struct sigaction act;
act.sa_handler = sig_handler;
sigaction(SIGINT, &act, NULL);
//all threads are created here
while (keep_running) {
printf("Press key + <enter>: ");
scanf("%s", keystr);
printf("\n");
key = keystr[0];
switch (key) {
//some cases and default here
}
}
pthread_join(comm_process_thread, NULL);
pthread_join(tcp_thread, NULL);
pthread_join(cifx_thread, NULL);
return EXIT_SUCCESS;
}