0

I have a code like this:

int main()
{
    int x=0;
    std::cout<<"Enter numbers"<<std::endl;
    while(std::cin>>x)
    {
        std::cout<<"Number entered: "<<x<<std::endl;
    }
    return 0;
}

When I press ctrl+c code gets terminated. I would like to print something like 'program terminated because ctrl+c was pressed. I know exception handling is a way. But is there any other alternative? By the way, I am running on linux.

naffarn
  • 526
  • 5
  • 12
C34nm
  • 27
  • 1

2 Answers2

1

No, exception handling has nothing to do with it.

You need to install a signal handler for the SIGINT signal using sigaction(2). Note that signal handling is asynchronous, and most C++ library classes and functions are not reentrant, so your signal handler is fairly limited insofar as what it can do. It can't touch std::cout, it can't do much. About the only thing it can do safely is using the write system call to write a canned message to standard output, before terminating with _exit().

It is possible to use the Linux-specific signal file descriptors to be able to handle signals in a safe manner, permitting the use of the C++ library

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Another useful thing to do in a signal handler is set an [atomic flag](http://en.cppreference.com/w/c/atomic/atomic_flag) so that code in the main thread can do something based on the information. – rvighne Aug 12 '16 at 01:55
0

In linux you can catch a signal SIGINT (this signal is emited when you press CTRL+C), a little example:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
/* procedure signal SIGINT */
static void sigint_handler (int signo)
{
  printf ("signal SIGINT!\n");
  exit (EXIT_SUCCESS);
}
int main (void)
{
    if (signal (SIGINT, sigint_handler) == SIG_ERR)
    {
         fprintf (stderr, "Error in SIGINT!\n");
         exit (EXIT_FAILURE);
    }
    for (;;)
    pause ( );
    return 0;
}
M. S.
  • 109
  • 7