Catch Ctrl-C in C Catch Ctrl-C in C c c

Catch Ctrl-C in C


With a signal handler.

Here is a simple example flipping a bool used in main():

#include <signal.h>static volatile int keepRunning = 1;void intHandler(int dummy) {    keepRunning = 0;}// ...int main(void) {   signal(SIGINT, intHandler);   while (keepRunning) {       // ...

Edit in June 2017: To whom it may concern, particularly those with an insatiable urge to edit this answer. Look, I wrote this answer seven years ago. Yes, language standards change. If you really must better the world, please add your new answer but leave mine as is. As the answer has my name on it, I'd prefer it to contain my words too. Thank you.


Check here:

Note: Obviously, this is a simple example explaining just how to set up a CtrlC handler, but as always there are rules that need to be obeyed in order not to break something else. Please read the comments below.

The sample code from above:

#include  <stdio.h>#include  <signal.h>#include  <stdlib.h>void     INThandler(int);int  main(void){     signal(SIGINT, INThandler);     while (1)          pause();     return 0;}void  INThandler(int sig){     char  c;     signal(sig, SIG_IGN);     printf("OUCH, did you hit Ctrl-C?\n"            "Do you really want to quit? [y/n] ");     c = getchar();     if (c == 'y' || c == 'Y')          exit(0);     else          signal(SIGINT, INThandler);     getchar(); // Get new line character}


Addendum regarding UN*X platforms.

According to the signal(2) man page on GNU/Linux, the behavior of signal is not as portable as behavior of sigaction:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

On System V, system did not block delivery of further instances of the signal and delivery of a signal would reset the handler to the default one. In BSD the semantics changed.

The following variation of previous answer by Dirk Eddelbuettel uses sigaction instead of signal:

#include <signal.h>#include <stdlib.h>static bool keepRunning = true;void intHandler(int) {    keepRunning = false;}int main(int argc, char *argv[]) {    struct sigaction act;    act.sa_handler = intHandler;    sigaction(SIGINT, &act, NULL);    while (keepRunning) {        // main loop    }}