Listing 12 A safe SIGINT handler that counts keyboard interrupts

/* ctrlc.c:    A safe SIGINT handler */
#include <stdio.h>
#include <signal.h>

void ctrlc_handler(int sig);

volatile sig_atomic_t ccount = 0;

main()
{
   char buf[BUFSIZ];

   /* Install SIGINT handler */
   if (signal(SIGINT,ctrlc_handler) == SIG_ERR)
      fputs("Error installing ctrl
            chandler\n",stderr);

   /* Do some I/O */
   while (gets(buf))
      puts(buf);

   /* Restore default handler */
   signal(SIGINT,SIG_DFL);
   printf("You pressed ctrlc %d times\n,ccount);
   return 0;
}

void ctrlc_handler(int sig)
{
   /* Re-install handler immediately */
   signal(sig,ctrlc_handler);

   ++ccount;
   return;
}

/* Sample Execution
c:>ctrlc
hello
hello
^C
there
there
^C
^Z
You pressed ctrlc 2 times
*/
/* End of File */