How do we properly kill a long infinite running thread by SIGINT?
Because what I'm doing is
volatile sig_atomic_t exitRequested = 0;
void sigint_handler()
{
printf("handler called\n");
exitRequested = 1;
}
void* process_tickers(void* _) {
while (1){
printf("ticker is running\n");
if (exitRequested == 1)
{
break;
}
if (dec_time == -1) {
size_t bufsize = 32;
char *buffer = malloc(32);
size_t characters;
characters = getline(&buffer,&bufsize,stdin);
if (characters > 0) {
//do something
}
}
}
return NULL;
}
Inside main I started the read by doing
int main() {
signal(SIGINT, sigint_handler);
pthread_t ticker_thread;
pthread_create(&ticker_thread, NULL, process_tickers, NULL);
insertRear(threads, &ticker_thread);
void ** retval = NULL;
pthread_join(ticker_thread, retval);
while (1)
{
//do something;
}
}
But I can't kill ticker_thread with SIGINT, because once I press the ctrl+c, the SIGINT would be sent to update the global variable exitRequested
but inside the thread function, getline()
would just sit there wait for program to enter something so it will go back to top of the loop and then it would break and by then thread will be reaped. How do I just kill thread immediately with Ctrl+C?
SIGINT
. Nor can you safely call functions such asprintf()
from within a signal handler. See stackoverflow.com/questions/2084830/…getline()
that's not interrupted on the signal. That should give you enough of a hint to figure this out...stdin
also involves the behavior of the input stream itself - is it a terminal? Has it been redirected to a file? It could even be a socket. See stackoverflow.com/questions/3882379/… for some more information. Andgetline()
is even harder to break thanfread()
because if you useselect()
onSTDIN_FILENO
, then callgetline()
it'll block still block if there's no newline but the stream is still open. And properly usingselect()
on standard input is hard.