Hi all,
Wondering what the best way to trigger a function ( so I can perform a graceful exit ) in a C++ console application on Ctrl+C is?
Hi all,
Wondering what the best way to trigger a function ( so I can perform a graceful exit ) in a C++ console application on Ctrl+C is?
Standard C way:
#include <signal.h>
void interrupted(int sig) {
/* do something ... */
exit(0);
}
int main(void) {
signal(SIGINT, interrupted);
/* now the problem can start up .... */
}
Usually you also want to connect SIGTERM, which is sent when a request to close the program is made. But the above suffices to handle Ctrl+C
You should take care not to do something time consuming in the handler. There is a race-condition: Whether or not the handler is set back to default is different among systems. Thus, if in your handler the user interrupts the program again, it will interrupt your handler and exit. Better to use sigaction
(that is however not Standard C), which doesn't have this problem.
You could do something like this:
#include <stdlib.h>
#include <signal.h>
void clean_up_func(int signum)
{
// perform some clean-up -- WARNING: functions called inside the
// signal handler should be reentrant!!
exit(0);
}
int main (int argc, char const *argv[])
{
// install the signal handler
signal(SIGINT, clean_up_func);
// do things
// call our clean up function
clean_up_func(SIGINT);
return 0;
}
Just be careful that you only call reentrant library functions from within your signal handler. SIGINT is the signal that handles aborts from things like CTRL+C.